Igo*_*Oks 35 c++ boost initialization member shared-ptr
我不确定初始化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);
}
Run Code Online (Sandbox Code Playgroud)
ere*_*eOn 30
您的代码非常正确(可行),但您可以使用初始化列表,如下所示:
C::C() :
mA(new A),
mB(new B(mA.get())
{
}
Run Code Online (Sandbox Code Playgroud)
哪个更正确,更安全.
如果,无论出于何种原因new A或new B投掷,你将没有泄漏.
如果new A抛出,则不分配内存,异常也会中止构造函数.什么都没有建成.
如果new B抛出,异常仍然会中止你的构造函数:mA将被正确破坏.
当然,由于实例B需要指向实例的指针A,因此成员的声明顺序很重要.
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.
| 归档时间: |
|
| 查看次数: |
34427 次 |
| 最近记录: |