Conversion from boost::shared_ptr to std::shared_ptr?

Based on janm’s response at first I did this: template<class T> std::shared_ptr<T> to_std(const boost::shared_ptr<T> &p) { return std::shared_ptr<T>(p.get(), [p](…) mutable { p.reset(); }); } template<class T> boost::shared_ptr<T> to_boost(const std::shared_ptr<T> &p) { return boost::shared_ptr<T>(p.get(), [p](…) mutable { p.reset(); }); } But then I realized I could do this instead: namespace { template<class SharedPointer> struct Holder { … Read more

Problems using member function as custom deleter with std::shared_ptr

std::shared_ptr<SDL_Surface>(SDL_LoadBMP(….), [=](SDL_Surface* surface) { std::cout << “Deleting surface\n”; SDL_FreeSurface(surface); }); or void DeleteSurface(SDL_Surface* surface) { std::cout << “Deleting surface\n”; SDL_FreeSurface(surface); } std::shared_ptr<SDL_Surface>(SDL_LoadBMP(….), DeleteSurface); EDIT: Seeing your updated question, DeleteSurface should be a non-member function, otherwise you need to use std::bind or std::mem_fn or some other member function pointer adapter.

Private constructor and make_shared

As mentioned, std::make_shared or its component parts don’t have access to private members. the call_once and once_flag are un-necessary. They are implicit in c++11 static initialisation, You normally would not want to expose the shared pointer.   class MyClass { MyClass() {} public: static MyClass& GetInstance() { static auto instance = MyClass(); return instance; } … Read more

weak_ptr, make_shared and memory deallocation

Is my understanding correct? Yes. If your weak_ptrs significantly outlive the (large) object and you are tight on memory, it may be beneficial to avoid make_shared. However, “large” here is measured by sizeof, and many conceptually “large” objects (for example, most standard containers, except std::array) are quite small by that metric, because they allocate additional … Read more

Example to use shared_ptr?

Using a vector of shared_ptr removes the possibility of leaking memory because you forgot to walk the vector and call delete on each element. Let’s walk through a slightly modified version of the example line-by-line. typedef boost::shared_ptr<gate> gate_ptr; Create an alias for the shared pointer type. This avoids the ugliness in the C++ language that … Read more