본문 바로가기

프로그래밍 언어/C,C++16

C++ range와 range iterator #include struct FibonacciIterator { bool operator!=(int x) const { return x >= current; } FibonacciIterator& operator++() { const auto tmp = current; current += last; last = tmp; return *this; } int operator*() const { return current; } private: int current{1}, last{1}; }; struct FibonacciRange { explicit FibonacciRange(int max) : max{ max } { } FibonacciIterator begin() const { return Fibonacci.. 2022. 3. 3.
C++ unique_ptr 직접 구현해 보기 #include #include #include template struct SimpleUniquePointer { SimpleUniquePointer() = default; SimpleUniquePointer(T* pointer) : pointer{ pointer } { } ~SimpleUniquePointer() { if(pointer) delete pointer; } SimpleUniquePointer(const SimpleUniquePointer&) = delete; SimpleUniquePointer& operator=(const SimpleUniquePointer&) = delete; SimpleUniquePointer(SimpleUniquePointer&& other) noexcept : p.. 2022. 3. 1.
C++ runtime polymorphism과 constructor injection, property injection enum class를 이용한 runtime polymorphism #include #include struct FileLogger { void log_transfer(long from, long to, double amount) { --snip-- printf("[file] %ld,%ld,%f\n", from, to, amount); } }; struct ConsoleLogger { void log_transfer(long from, long to, double amount) { printf("[cons] %ld -> %ld: %f\n", from, to, amount); } }; enum class LoggerType { Console, File }; struct Bank { Bank() : type .. 2022. 2. 28.
스마트 포인터 스마트 포인터(smart pointer)는 객체를 소요하며, 스마트 포인터의 생명주기는 객체와 같거나 길어야 한다. scoped pointers stdlib에 있는 포인터가 아니다. boost/smart/scoped_ptr.hpp에 있다. scoped pointer는 어떤 스코프(scope)에서 다른 스코프로 옮겨질 수 없다.(non-transferable) 그리고 객체를 복사할 수 없으며(exclusive ownership), 다른 스마트 포인터가 스코프 포인터의 동적 객체의 소유권을 가질 수 없다. boost::scoped_ptr my_ptr{ new PointedToType }; 보통 다아나믹 객체를 new를 이용해 생성한 다음, 위처럼 생성자에게 넘겨 준다. unique pointer transf.. 2021. 9. 4.
C++ explicit implicit type conversion을 막아준다. #include class A { public: int num; A(int n) : num(n) {}; }; void printA(A a) { std::cout 2021. 8. 18.
C++ const_cast, static_cast, reinterpret_cast named conversion을 이용해 하나의 타입에서 다른 타입으로 명시적으로 형변환을 할 수 있다. 보통 implicit conversion을 사용하지 못할 때 쓴다. 대개 아래와 같은 형식을 취한다. named-conversion(object-to-cast) const_cast const 변수를 받아 const를 벗겨준다.(cast away) void carbon_thaw(const int& encased_solo) { //encased_solo++; // Compiler error; modifying const auto& hibernation_sick_solo = const_cast(encased_solo); hibernation_sick_solo++; } const_cast를 이용해 volati.. 2021. 8. 18.
C++ copy and move constructor, assignment 이 글에서는 C++의 copy semantic과 move sematic에 대해서 알아봅니다. 객체(object)를 복사(copy)하는 방법에는 copy constructor, copy assignment 두 가지 방법이 있다. 먼저 '복사'의 의미를 알아보자. 객체 x를 객체 y로 '복사'한다는 것은 두 객체가 동등(equivalent)하지만 독립적(independent)이라는 뜻이다. 즉, 복사 후에 x == y이지만, 객체 x에 대한 수정은 객체 y에 영향을 주지 않는다. 예를 들어, 객체를 함수의 인자에 값으로 넘겨줄 때(pass by value) 복사가 일어난다. #include int add_one_to(int x) { x++; return x; } int main() { auto origina.. 2021. 8. 18.