如何初始化作为类成员的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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码非常正确(它可以工作),但是您可以使用初始化列表,如下所示:
这更加正确且安全。
无论出于何种原因,如果
new A
或new B
抛出异常,则不会发生泄漏。如果 new A 抛出,则不会分配内存,并且异常也会中止您的构造函数。什么也没建造。
如果
new B
抛出,异常仍会中止您的构造函数:mA
将被正确析构。当然,由于
B
的实例需要一个指向A
实例的指针,因此成员的声明顺序很重要。在您的示例中,成员声明顺序是正确的,但如果颠倒过来,那么您的编译器可能会抱怨
mB
在mA
和mB 实例化之前初始化
可能会失败(因为mA
尚未构造,因此调用mA.get()
会调用未定义的行为)。我还建议您使用
shared_ptr
而不是A*
作为B
构造函数的参数(if 这是有道理的,如果你能接受一点点开销的话)。可能会更安全。也许可以保证
B
的实例不能在没有A
的实例的情况下生存,然后我的建议就不适用,但是我们在这里缺乏上下文来给出一个对此的明确建议。Your code is quite correct (it works), but you can use the initialization list, like this:
Which is even more correct and as safe.
If, for whatever reason,
new A
ornew 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 ofA
, 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 beforemA
and the instantiation ofmB
would likely fail (sincemA
would not be constructed yet, thus callingmA.get()
invokes undefined behavior).I would also suggest that you use a
shared_ptr<A>
instead of aA*
as a parameter for yourB
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 ofA
and then my advice doesn't apply, but we're lacking of context here to give a definitive advice regarding this.