Search code examples
c++shared-ptrunique-ptrmove-assignment-operator

Assigning make_unique<X> to shared_ptr<X>


I (erroneously) had the following assignment in my program:

std::shared_ptr<SI::Program> m_program; // in class

m_program = std::make_unique<SI::Program>(); // in method

When I found this, I first wondered why this even compiles. It turns out the shared_ptr has a special move assignment operator for unique_ptr objects.

My question is, is this therefore always safe to do, or does it have any implications?

(Safe as for the code execution; it is obviously not safe for a code review...)


Solution

  • It is "safe" to do so in a sense that you won't have any double-deleting or other problems.

    It is not OK to do so because:

    1. It's misleading - make_unique is used to make unique pointers, not shared.
    2. It's wasteful - make_unique will only allocate the object, not the associated control block. that will force the shared_ptr constructor to allocate the control block itself. std::make_shared allocate them both in one allocation, which is much more efficient.