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...)
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:
make_unique
is used to make unique pointers, not shared. 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.