如何初始化作为类成员的 shared_ptr?
我不确定初始化作为类成员的 shared_ptr
的好方法.你能告诉我,我在C::foo()
中选择的方式是否合适,或者有更好的解决方案吗?
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())
{
}
哪个更正确,更安全.
如果,无论什么原因,new A
或 new B
抛出,你就没有泄漏.
If, for whatever reason, new A
or new B
throws, you'll have no leak.
如果 new A
抛出,则不会分配内存,异常也会中止您的构造函数.什么都没有构建.
If new A
throws, then no memory is allocated, and the exception aborts your constructor as well. Nothing was constructed.
如果 new B
抛出,并且异常仍会中止构造函数:mA
将被正确销毁.
If new B
throws, and the exception will still abort your constructor: mA
will be destructed properly.
当然,由于 B
的实例需要一个指向 A
实例的指针,成员的声明顺序很重要.
Of course, since an instance of B
requires a pointer to an instance of A
, the declaration order of the members matters.
成员声明顺序在您的示例中是正确的,但如果它被颠倒了,那么您的编译器可能会抱怨 mB
在 mA
之前被初始化和 mA
的实例化code>mB 可能会失败(因为尚未构造 mA
,因此调用 mA.get()
会调用未定义的行为).
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).
我还建议您使用 shared_ptr
而不是 A*
作为 B
构造函数的参数(<强>如果它有意义并且您是否可以接受小开销).可能会更安全.
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.
也许可以保证 B
的实例离不开 A
的实例,然后我的建议不适用,但我们在这里缺乏上下文就此给出明确的建议.
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.
相关文章