std::shared_ptr of this

There is std::enable_shared_from_this just for this purpose. You inherit from it and you can call .shared_from_this() from inside the class. Also, you are creating circular dependencies here that can lead to resource leaks. That can be resolved with the use of std::weak_ptr. So your code might look like this (assuming children rely on existence of … Read more

std::shared_ptr thread safety

What you’re reading isn’t meaning what you think it means. First of all, try the msdn page for shared_ptr itself. Scroll down into the “Remarks” section and you’ll get to the meat of the issue. Basically, a shared_ptr<> points to a “control block” which is how it keeps track of how many shared_ptr<> objects are … Read more

Why do std::shared_ptr work

The trick is that std::shared_ptr performs type erasure. Basically, when a new shared_ptr is created it will store internally a deleter function (which can be given as argument to the constructor but if not present defaults to calling delete). When the shared_ptr is destroyed, it calls that stored function and that will call the deleter. … Read more

Why isn’t there a std::shared_ptr specialisation?

The LWG (Library Working Group of the C++ committee) briefly considered the possibility but the idea wasn’t without controversy. Though the controversy was mainly about a feature added to the shared_ptr<T[]> proposal that could have been jettisoned (arithmetic on shared_ptr<T[]>). But ultimately the real real reason is that though it was discussed, there was never … Read more

When is std::weak_ptr useful?

std::weak_ptr is a very good way to solve the dangling pointer problem. By just using raw pointers it is impossible to know if the referenced data has been deallocated or not. Instead, by letting a std::shared_ptr manage the data, and supplying std::weak_ptr to users of the data, the users can check validity of the data … Read more

Difference in make_shared and normal shared_ptr in C++

The difference is that std::make_shared performs one heap-allocation, whereas calling the std::shared_ptr constructor performs two. Where do the heap-allocations happen? std::shared_ptr manages two entities: the control block (stores meta data such as ref-counts, type-erased deleter, etc) the object being managed std::make_shared performs a single heap-allocation accounting for the space necessary for both the control block … Read more

shared_ptr to an array : should it be used?

With C++17, shared_ptr can be used to manage a dynamically allocated array. The shared_ptr template argument in this case must be T[N] or T[]. So you may write shared_ptr<int[]> sp(new int[10]); From n4659, [util.smartptr.shared.const] template<class Y> explicit shared_ptr(Y* p); Requires: Y shall be a complete type. The expression delete[] p, when T is an array … Read more