“Downcasting” unique_ptr to unique_ptr

I’d create a couple of function templates, static_unique_ptr_cast and dynamic_unique_ptr_cast. Use the former in cases where you’re absolutely certain the pointer is actually a Derived *, otherwise use the latter. template<typename Derived, typename Base, typename Del> std::unique_ptr<Derived, Del> static_unique_ptr_cast( std::unique_ptr<Base, Del>&& p ) { auto d = static_cast<Derived *>(p.release()); return std::unique_ptr<Derived, Del>(d, std::move(p.get_deleter())); } template<typename … Read more

Why does unique_ptr have the deleter as a type parameter while shared_ptr doesn’t?

Part of the reason is that shared_ptr needs an explicit control block anyway for the ref count and sticking a deleter in isn’t that big a deal on top. unique_ptr however doesn’t require any additional overhead, and adding it would be unpopular- it’s supposed to be a zero-overhead class. unique_ptr is supposed to be static. … Read more

std::shared_ptr initialization: make_shared() vs shared_ptr(new Foo) [duplicate]

Both examples are rather more verbose than necessary: std::shared_ptr<int> p(new int); // or ‘=shared_ptr<int>(new int)’ if you insist auto p = std::make_shared<int>(); // or ‘std::shared_ptr<int> p’ if you insist What’s the difference? The main difference is that the first requires two memory allocations: one for the managed object (new int), and one for the reference … Read more

Why can’t a weak_ptr be constructed from a unique_ptr?

If you think about it, a weak_ptr must refer to something other than the object itself. That’s because the object can cease to exist (when there are no more strong pointers to it) and the weak_ptr still has to refer to something that contains the information that the object no longer exists. With a shared_ptr, … 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

Is auto_ptr deprecated?

UPDATE: This answer was written in 2010 and as anticipated std::auto_ptr has been deprecated. The advice is entirely valid. In C++0x std::auto_ptr will be deprecated in favor of std::unique_ptr. The choice of smart pointer will depend on your use case and your requirements, with std::unique_ptr with move semantics for single ownership that can be used … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)