C++ 如何初始化作为类成员的 shared_ptr?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3545450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:05:20  来源:igfitidea点击:

How to initialize a shared_ptr that is a member of a class?

c++boostinitializationshared-ptrmember

提问by Igor Oks

I am not sure about a good way to initialize a shared_ptrthat is a member of a class. Can you tell me, whether the way that I choose in C::foo()is fine, or is there a better solution?

我不确定初始化shared_ptr一个类的成员的好方法。你能告诉我,我选择的方式是否C::foo()合适,或者有更好的解决方案吗?

class A
{
  public:
    A();
};

class B
{
  public:
    B(A* pa);
};

class C
{
    boost::shared_ptr<A> mA;
    boost::shared_ptr<B> mB;
    void foo();
};

void C::foo() 
{
    A* pa = new A;
    mA = boost::shared_ptr<A>(pa);
    B* pB = new B(pa);
    mB = boost::shared_ptr<B>(pb);
}

采纳答案by ereOn

Your code is quite correct (it works), but you can use the initialization list, like this:

您的代码非常正确(它有效),但您可以使用初始化列表,如下所示:

C::C() :
  mA(new A),
  mB(new B(mA.get())
{
}

Which is even more correct and as safe.

哪个更正确,更安全。

If, for whatever reason, new Aor new Bthrows, you'll have no leak.

如果,无论出于何种原因,new Anew B抛出,你就没有泄漏。

If new Athrows, then no memory is allocated, and the exception aborts your constructor as well. Nothing was constructed.

如果new A抛出,则不会分配内存,异常也会中止您的构造函数。什么都没有建造。

If new Bthrows, and the exception will still abort your constructor: mAwill be destructed properly.

如果new B抛出,并且异常仍将中止您的构造函数:mA将被正确销毁。

Of course, since an instance of Brequires a pointer to an instance of A, the declaration order of the members matters.

当然,由于 的实例B需要指向实例的指针A,因此成员的声明顺序很重要

The member declaration order is correct in your example, but if it was reversed, then your compiler would probably complain about mBbeeing initialized before mAand the instantiation of mBwould likely fail (since mAwould not be constructed yet, thus calling mA.get()invokes undefined behavior).

成员声明顺序在您的示例中是正确的,但如果它被颠倒了,那么您的编译器可能会抱怨mB之前被初始化mA并且实例化mB可能会失败(因为mA尚未构造,因此调用会mA.get()调用未定义的行为)。



I would also suggest that you use a shared_ptr<A>instead of a A*as a parameter for your Bconstructor (ifit makes senses and if you can accept the little overhead). It would probably be safer.

我还建议您使用 ashared_ptr<A>而不是 aA*作为B构造函数的参数(如果有意义并且您可以接受少量开销)。应该会更安全。

Perhaps it is guaranteed that an instance of Bcannot live without an instance of Aand then my advice doesn't apply, but we're lacking of context here to give a definitive advice regarding this.

也许可以保证 的实例B不能没有 的实例,A然后我的建议不适用,但是我们这里缺乏上下文来就此给出明确的建议。