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
How to initialize a shared_ptr that is a member of a class?
提问by Igor Oks
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?
我不确定初始化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 A
or new B
throws, you'll have no leak.
如果,无论出于何种原因,new A
或new B
抛出,你就没有泄漏。
If new A
throws, then no memory is allocated, and the exception aborts your constructor as well. Nothing was constructed.
如果new A
抛出,则不会分配内存,异常也会中止您的构造函数。什么都没有建造。
If new B
throws, and the exception will still abort your constructor: mA
will be destructed properly.
如果new B
抛出,并且异常仍将中止您的构造函数:mA
将被正确销毁。
Of course, since an instance of B
requires 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 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).
成员声明顺序在您的示例中是正确的,但如果它被颠倒了,那么您的编译器可能会抱怨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 B
constructor (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 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.
也许可以保证 的实例B
不能没有 的实例,A
然后我的建议不适用,但是我们这里缺乏上下文来就此给出明确的建议。