c++ - std::shared_ptr 初始化:make_shared<Foo>() 与 shared_ptr<T>(new Foo)

标签 c++ c++11 shared-ptr smart-pointers

<分区>

有什么区别:

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/

相关文章:

c++ - SFML/C++ Sprite 由于超出范围而显示为白框,不知道在哪里

c++ - 为什么在 glsl 中使用实例化时纹理缓冲区比顶点输入快?

C++ lambda 返回类型不是预期的

linux - 枚举类型声明的 C++11 编译错误如预期的那样在数字常量之前

c++ - 将std::shared_ptr <T>传递给采用std::shared_ptr <const T>的函数?

C++ 比较共享指针的堆栈

c++ - UE4因为简单的旋转脚本崩溃

c++ - 使用可变参数列表初始化表

c++ - 迭代时从 STL 容器中查找并删除元素

c++ - 使用多个 ifstreams 作为 ifstreams 的 vector