shared_ptr的缺点 [英] Disadvantages of shared_ptr
问题描述
通过包含在c ++ 11中的shared_ptr,可以实现半垃圾回收环境。
With shared_ptr included in c++11, one could achieve a semi garbage-collected enviroment. Does the (inflationary?) usage come along with some disadvantages?
我可以想象一个类模型,你可以在其中创建一个类,在该类中,你的类在最后是typedef a shared_ptr以缩写语法。
I could imagine a class model, where you create a class in which you typedef your class at the end as a shared_ptr to abbreviate the syntax.
/////////////////
//// MyClass ////
/////////////////
#include <memory>
class MyClass {
public:
Myclass();
};
typedef std::shared_ptr<MyClass> SharedMyClass;
///////////////////////
//// Example Class ////
///////////////////////
class Example {
public:
Example(): myClassObject(new MyClass()) {}
private:
SharedMyClass myClassObject;
};
推荐答案
当然还有一些缺点:保持引用计数,并且每次复制或销毁一个 shared_ptr
实例时,此引用计数必须递增和递减。如果你的程序使用多个线程,那么引用计数的操作必须以线程安全的方式进行,这会增加一些额外的开销,其大小取决于实现。
Of course there are disadvantages: you require extra memory to maintain a reference count, and every time you copy or destroy a shared_ptr
instance this reference count has to be incremented and decremented. If your program uses multiple threads then the manipulation of the reference count has to be done in a thread-safe manner, which can add some additional overhead, the magnitude of which depends on the implementation.
这种开销是否以整体负面影响您的程序取决于您的程序的详细信息。一般来说,你应该只使用 std :: shared_ptr
用于真正需要共享的资源,因为它可能有点任意的对象最后需要它们。在其他情况下,单个所有权点通常更容易维护,因为您确切知道每个资源将活动的时间。
Whether or not this overhead impacts your program in an overall negative way depends on the details of your program. Generally you should only use std::shared_ptr
for resources that truly need to be shared, because it can be somewhat arbitrary which object will need them last. In other cases, a single point of ownership is usually easier to maintain because you know exactly how long each resource will be alive.
此外,您需要注意 std :: shared_ptr
不是对象生命周期管理的灵丹妙药。特别是,如果你有两个对象,每个对象都拥有一个 std :: shared_ptr
,那么对象将拥有循环所有权,并且永远不会被自动删除,除非你先中断循环通过在其中一个上调用 reset()
。
Additionally, you need to be aware that std::shared_ptr
is not a panacea for object lifetime management. In particular, if you have two objects that each own an std::shared_ptr
to the other, the objects have cyclic ownership and will never be automatically deleted unless you first break the cycle by invoking reset()
on one of them.
这篇关于shared_ptr的缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!