A Simple Smart Pointer Implementation in C++

A Simple Smart Pointer Implementation in C++ Originally published in Chinese on 2021-02-21; this English edition preserves the original scope and technical context. 1 std::auto_ptr In C++, memory leaks often occur due to the lack of delete for pointers, such as with an Object template class class: cpp template class Object { public: ~Object() { delete this->ptr; } void* ptr; }; template<typename T> class Object { public: // constructor Object() : t_() { cout << "Object::Constructor " << this << endl; } Object(T t) : t_(t) { cout << "Object::Constructor " << this << endl; } // copy-ctor Object(const Object &other) { cout << "Object::Copy-ctor " << this << endl; } // destructor ~Object() { cout << "Object::Destructor " << this << endl; } void Set(T t) { t_ = t; } void Print() { cout << t_ << endl; } private: T t_; }; If objects of a class are allocated on the heap and not deallocated when their scope is exited, a memory leak occurs: ...

February 21, 2021 · 15 min · Zhengyu Chen

Closures and Anonymous Functions in C++

Closures and Anonymous Functions in C++ Originally published in Chinese on 2020-11-14; this English edition preserves the original scope and technical context. This blog post primarily introduces the concepts of closures and functors in C++. 1 Closure and Functors A closure (also known as a lexical closure or function closure) can be understood as an operation that comes with attached data. Wikipedia defines a closure in programming languages as: “In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions.” There are two layers of meaning: ...

November 14, 2020 · 9 min · Zhengyu Chen