Search code examples
c++c++11smart-pointers

Constructing shared_ptr from unique_ptr with and without move?


I see in the highly-upvoted answer here (https://stackoverflow.com/a/37885232/3754760) there are two ways to convert a unique_ptr to a shared_ptr, namely by creating the unique_ptr first and then move-ing it to the shared_ptr, as well as assigning the unique_ptr directly to the shared_ptr.

Example:

std::unique_ptr<std::string> unique = std::make_unique<std::string>("test");
std::shared_ptr<std::string> shared = std::move(unique);

or:

std::shared_ptr<std::string> shared = std::make_unique<std::string>("test");

Are the two above equivalent, performance-wise? Secondly, I see a warning like Moving a temporary object prevents copy elision when doing something like this:

std::shared_ptr<std::string> shared = std::move(std::make_unique<std::string>("test"));

As someone pretty new to smart pointers, could someone explain what this warning means and why it occurs in the 3rd example? Thanks!


Solution

  • Are the two above equivalent

    Yes

    could someone explain what this warning means and why it occurs in the 3rd example?

    Copy Elison only works when the result of a function call returning a temp object is directly assigned to a variable. The compiler can optimize away the temp object and let the function initialize the variable directly. But in the 3rd example, there is an intermediate type-cast being performed between the construction of the temp object and the assignment of the temp object to a variable, so the temp object can't be optimized away.