简体   繁体   English

std :: shared_ptr初始化

[英]std::shared_ptr initialization

What is the difference between: 之间有什么区别?

std::shared_ptr<int> p1 = std::shared_ptr<int>(new int);

and

std::shared_ptr<int> p2 = (std::shared_ptr<int>) new int;

Which is better and why? 哪个更好?为什么?

Neither. 都不行 This one is strictly preferable: 这是绝对可取的:

auto p3 = std::make_shared<int>();

(Although it has slightly different semantics, since it initializes the int object, unlike your code.) (尽管它的语义略有不同,因为它初始化int对象,这与您的代码不同)。

This version is subexpression-wise correct, doesn't contain the red-flag word "new", and also uses a more efficient allocation scheme. 此版本在子表达式方面是正确的,不包含红色标记词“ new”,并且还使用了更有效的分配方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM