C++

    10. STL tuple

    10. STL tuple

    C++ Stl 중에 튜플이 있다. 사용하는데 편한데 어떻게 만들어져있는지 궁금할정도로 신기하다 void main() { std::tuple t; std::get(t) = 1.2f; std::get(t) = 1; printf("%g\r\n", std::get(t)); printf("%i\r\n", std::get(t)); } 출력 1.2 1 이 튜플을 비슷하게 만들어보자 더보기 template struct seq{}; template struct make_seq : make_seq { }; template struct make_seq { typedef seq type; }; template using MakeSeq = typename make_seq::type; template struct foo_stor..

    9. STL Equality and Equivalence

    예전부터 많이 사용하는 그런 기능이라 이틀 연속으로 올리네 허헣... 졸리다... 일단 간단한 코드 먼저 보자 #include #include void main() { std::set s1; s1.insert(1); s1.insert(5); s1.insert(2); for (int v : s1) { printf("%i\r\n", v); } } 여기서 사용하는 set은 RB트리로 값이 있는지 없는지 유무만 판단하기 위해 담아두는 자료구조이다. 대신 탐색 시간을 단축하기 위해 정렬해서 값이 들어간다. 기본값은 오름차순이다. 따라서 위에 코드를 실행시키면 1 2 5 이런식으로 나오게 된다. 만약, int형이 아니고 직접 정의한 클래스나 구조체를 넣어보자 #include #include class KPoint ..

    8. STL Custom Allocator

    std의 Container들에는 Allocator(할당자)가 존재한다. 이 Allocator들은 Container들의 메모리를 관리한다. 기본적으로 표준의 Allocator를 사용하지만, 사용자가 직접 만들어준다면, 자신이 만든 Allocator를 사용할 수 있다. 일단 흔히 사용하고 있는 vector에 있는 오버로딩된 함수를 보자 std::vector temp; 이 vector의 템플릿을 한번 보게 되면, template class vector { // varying size array of values private: template friend class _Vb_val; friend _Tidy_guard; using _Alty = _Rebind_alloc_t; using _Alty_traits = ..

    7. CRTP, Static Plymophism and Rebind

    후... 연말, 연초에는 안바쁠거라고 하던 회사는 거짓말쟁이다. 야근밖에 안했다.. ㅠㅠ CRTP(Curiously Recurring Template Pattern) - 기반 클래스에서 파생 클래스의 이름을 사용할 수 있게 하는 기법 - 파생 클래스를 만들 때 기반 클래스의 템플릿 인자로 파생 클래스 이름을 전달. 이름부터 이상한 반복 템플릿 패턴이다. 어떻게 사용되는지 3개의 예시로 보자 Counter template struct counter { static int objects_created; static int objects_alive; counter() { ++objects_created; ++objects_alive; } protected: ~counter() { --objects_alive;..

    6. STL Placement new

    C++ STL 중 vector에 값을 넣고 뺄때 push_back을 사용해서 넣는다. 이렇게 넣을때, vector 내부에서는 연결돼있는 배열에 값을 넣고 만약 그 크기가 다 차게 되면 더 많은 메모리를 재 할당하여 사용하게 된다. 만약, 여기서 값을 빼고 해제를 하고싶어 delete를 사용해서 중간에 있는 값을 해제하게 되면!?!???! 연결돼있는 배열에서 중간의 값이 빠지면서 메모리가 큰일 날것이다.(안해봐서 모르는데 위험해보이긴 한다. 맨 처음값이 배열의 크기를 담당하는데 연속되는 중간에 값이 없으니까) 간단히 알아보자 #include #include #include char buffer[1024]; class KTest { unsigned int _iData; public: KTest() { _iD..

    5. Operator Overloading03 operator new

    32비트 환경이다. 간단한 클래스 부터 보자 #include int buffer[1024] = {0}; class KTest { public: KTest() { printf("KTest()\r\n"); } ~KTest() { printf("~KTest()\r\n"); } private: int i = 3; }; void main() { KTest* p; p = new KTest; delete p; } 출력 : KTest() ~KTest() 생성자 소멸자를 호출하는 간단한 생성자이다. C++ 클래스에서 생성자를 호출하여 동적으로 할당할 때 메모리 할당(new) -> 생성자 호출(KTest()) 그리고 해제 할때는 소멸자 호출(~KTest()) -> 메모리 해제(delete) 이런 순서로 작동한다. 메모리를..

    4. Operator Overloading Ostream

    이번에는 C++에서 흔히 사용하는 std::cout을 만들어보자 class ostream { public: const ostream& Print(const int i) const { printf("%i", i); return *this; } const ostream& Print(const float f) const { printf("%f", f); return *this; } const ostream& Print(const char* s) const { printf("%s", s); return *this; } }; 이런식으로 정의하게 되면 ostream cout; int main() { int i = 3; float f = 4.1f; cout.Print(i).Print(f).Print("Hello");..

    3. Operator Overloading Function

    C++이나 C#에서 string을 정의 및 연산을 할때 사용하는 명령어를 간단하게 만들어 보자. 보통 문자열 데이터를 선언할 때 string s = "hello"; 이런식으로 선언 할 것이다. 이렇게 선언하는 방법을 만들어보자. class string { public: string(const char* s = nullptr) { if (s == nullptr) { buffer[0] = NULL; } else { strcpy_s(buffer, s); } } const char* c_str() const { return buffer; } private: char buffer[100]; }; (임시로 문자열 최대 크기는 100으로 잡아놨다.) 이런식으로 선언 한다. 이렇게 하고 위의 명령어를 실행 하면 hel..