Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...)

like image 536
Felix Dombek Avatar asked Aug 18 '16 15:08

Felix Dombek


2 Answers

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.
like image 184
David Haim Avatar answered Nov 16 '22 19:11

David Haim


Yes, that's perfectly safe; shared_ptr has a constructor that can transfer ownership from a unique_ptr by move. Though it's not as efficient as calling make_shared properly.

like image 21
Nicol Bolas Avatar answered Nov 16 '22 19:11

Nicol Bolas