如何初始化一个shared_ptr这是一个类的成员? [英] How to initialize a shared_ptr that is a member of a class?

查看:1707
本文介绍了如何初始化一个shared_ptr这是一个类的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道要初始化的shared_ptr 这是一个类的成员的好方法。你能告诉我,无论我在选择中c :: foo的()是罚款,还是有一个更好的解决方案?

  A级
{
  上市:
    一个();
};B类
{
  上市:
    B(A * PA);
};C类
{
    提高:: shared_ptr的< A>嘛;
    提高:: shared_ptr的< B> MB;
    无效美孚();
};无效Ç:: foo的()
{
    A * PA =新A;
    MA =升压:: shared_ptr的< A>(PA);
    B * PB =新B(PA);
    MB =提高:: shared_ptr的< B>(PB);
}


解决方案

您code是完全正确的(它的工作),但你可以使用初始化列表,像这样的:

 Ç:: C():
  MA(新一),
  MB(新B(mA.get())
{
}

这更加正确和安全的。

如果出于某种原因,新A 新型B 罚球,你有没有泄漏。

如果新A 两罚全中,然后将不会分配内存,异常中止你的构造以及。没有被修建了。

如果新型B 抛出,异常仍然会终止你的构造:毫安会得到妥善销毁<。 / p>

当然,由于 B 的一个实例,需要一个指向 A 的一个实例,该声明顺序成员事项

成员声明顺序是你的榜样正确的,但如果它发生了逆转,那么你的编译器可能会抱怨 MB beeing初始化毫安 MB的实例可能会失败(因为毫安不会被尚未建成,因此调用 mA.get()调用不确定的行为)。


我也建议你使用的shared_ptr&LT; A&GT; ,而不是 A * 作为一个参数你的 B 构造函数(如果它使感官,如果你能接受小的开销)。它可能会更安全。

或许可以保证 B 生活中不可缺少的一个实例的实例 A 然后我的意见没有按T适用,但我们缺乏的背景下在这里给这方面一个明确的意见。

I am not sure about a good way to initialize a shared_ptr that 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?

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);
}

解决方案

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 A or new B throws, you'll have no leak.

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

If new B throws, and the exception will still abort your constructor: mA will be destructed properly.

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

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


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

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

这篇关于如何初始化一个shared_ptr这是一个类的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆