std :: shared_ptr初始化:make_shared< Foo>()vs shared_ptr< T>(new Foo) [英] std::shared_ptr initialization: make_shared<Foo>() vs shared_ptr<T>(new Foo)
问题描述
之间有什么区别:
std::shared_ptr<int> p = std::shared_ptr<int>( new int );
和
std::shared_ptr<int> p = std::make_shared< int >();
?
为什么?
P。非常确定这一定已经回答了,但我找不到类似的问题。
P. S. Pretty sure this must have been answered already, but I can't find a similar question.
推荐答案
比必要的更详细:
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
应该分配一块内存,并在其中创建两个。
The main difference is that the first requires two memory allocations: one for the managed object (new int
), and one for the reference count. make_shared
should allocate a single block of memory, and create both in that.
Which one should I prefer and why?
您通常应使用 make_shared
它更高效。正如在另一个答案中所指出的,它还避免了任何内存泄漏的可能性,因为你从来没有一个指向被管对象的原始指针。
You should usually use make_shared
as it's more efficient. As noted in another answer, it also avoids any possibility of a memory leak, since you never have a raw pointer to the managed object.
但是, ,它有一个潜在的缺点,即当对象被破坏时,如果仍然有弱指针阻止共享计数被删除,则不会释放内存。
However, as noted in the comments, it has a potential disadvantage that the memory won't be released when the object is destroyed, if there are still weak pointers preventing the shared count from being deleted.
这篇关于std :: shared_ptr初始化:make_shared< Foo>()vs shared_ptr< T>(new Foo)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!