从 unique_ptr 构造 shared_ptr 有没有移动?
Constructing shared_ptr from unique_ptr with and without move?
我在此处 () 的高度赞成答案中看到,有两种方法可以将 unique_ptr 转换为 shared_ptr,即创建 unique_ptr首先然后 move
-ing 它到 shared_ptr,以及将 unique_ptr 直接分配给 shared_ptr.
示例:
std::unique_ptr<std::string> unique = std::make_unique<std::string>("test");
std::shared_ptr<std::string> shared = std::move(unique);
或:
std::shared_ptr<std::string> shared = std::make_unique<std::string>("test");
以上两个在性能方面是否等效?其次,我在做这样的事情时看到了像 Moving a temporary object prevents copy elision
这样的警告:
std::shared_ptr<std::string> shared = std::move(std::make_unique<std::string>("test"));
作为智能指针的新手,有人可以解释这个警告的含义以及为什么它会出现在第三个示例中吗?谢谢!
Are the two above equivalent
是
could someone explain what this warning means and why it occurs in the 3rd example?
Copy Elison 仅在函数调用返回临时对象的结果 直接 分配给变量时有效。编译器可以优化掉临时对象,让函数直接初始化变量。但是在第三个示例中,在构造临时对象和将临时对象赋值给变量之间执行了中间类型转换,因此无法优化临时对象。
我在此处 (move
-ing 它到 shared_ptr,以及将 unique_ptr 直接分配给 shared_ptr.
示例:
std::unique_ptr<std::string> unique = std::make_unique<std::string>("test");
std::shared_ptr<std::string> shared = std::move(unique);
或:
std::shared_ptr<std::string> shared = std::make_unique<std::string>("test");
以上两个在性能方面是否等效?其次,我在做这样的事情时看到了像 Moving a temporary object prevents copy elision
这样的警告:
std::shared_ptr<std::string> shared = std::move(std::make_unique<std::string>("test"));
作为智能指针的新手,有人可以解释这个警告的含义以及为什么它会出现在第三个示例中吗?谢谢!
Are the two above equivalent
是
could someone explain what this warning means and why it occurs in the 3rd example?
Copy Elison 仅在函数调用返回临时对象的结果 直接 分配给变量时有效。编译器可以优化掉临时对象,让函数直接初始化变量。但是在第三个示例中,在构造临时对象和将临时对象赋值给变量之间执行了中间类型转换,因此无法优化临时对象。