<分区>
有什么区别:
std::shared_ptr<int> p = std::shared_ptr<int>( new int );
和
std::shared_ptr<int> p = std::make_shared< int >();
?
我应该选择哪一个,为什么?
P. S. 很确定这一定已经有人回答了,但我找不到类似的问题。
<分区>
有什么区别:
std::shared_ptr<int> p = std::shared_ptr<int>( new int );
和
std::shared_ptr<int> p = std::make_shared< int >();
?
我应该选择哪一个,为什么?
P. S. 很确定这一定已经有人回答了,但我找不到类似的问题。
最佳答案
这两个例子都比必要的更冗长:
std::shared_ptr<int> p(new int); // or '=shared_ptr<int>(new int)' if you insist
auto p = std::make_shared<int>(); // or 'std::shared_ptr<int> p' if you insist
What's the difference?
主要区别在于第一个需要两次内存分配:一次用于托管对象 (new int
),一次用于引用计数。 make_shared
应该分配一个内存块,并在其中创建两个内存块。
Which one should I prefer and why?
您通常应该使用 make_shared
,因为它效率更高。如另一个答案所述,它还避免了任何内存泄漏的可能性,因为您永远不会有指向托管对象的原始指针。
但是,如评论中所述,如果仍有弱指针阻止共享计数被删除,则它有一个潜在的缺点,即当对象被销毁时内存不会被释放。
编辑 2020/03/06:
更多建议也来自 official Microsoft documentation与相关的例子。将注意力集中在示例 1 代码段上:
Whenever possible, use the make_shared function to create a shared_ptr when the memory resource is created for the first time. make_shared is exception-safe. It uses the same call to allocate the memory for the control block and the resource, which reduces the construction overhead. If you don't use make_shared, then you have to use an explicit new expression to create the object before you pass it to the shared_ptr constructor. The following example shows various ways to declare and initialize a shared_ptr together with a new object.
关于c++ - std::shared_ptr 初始化:make_shared<Foo>() 与 shared_ptr<T>(new Foo),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25718227/