【问题标题】:boost::shared_ptr as data member, how to assign in the constructor?boost::shared_ptr 作为数据成员,如何在构造函数中赋值?
【发布时间】:2013-11-20 21:45:59
【问题描述】:

如果你的类中有 b​​oost::shared_ptr 数据成员:

class X{
public:

private:
    boost::shared_ptr<Y> a;
};

如何在X的构造函数中初始化指针?我试过了,它不起作用:

X::X(){
    a(new Y());
}

【问题讨论】:

  • “不起作用”怎么办?我觉得不错

标签: c++ memory-management boost shared-ptr


【解决方案1】:

你必须使用成员初始化器列表:

X::X()
    : a(new Y())
//  ^^^^^^^^^^^^
{ }

否则a(new Y()) 被认为是对没有定义(或原型)的boost::shared_ptr&lt;Y&gt;::operator()(Y*) 的调用,因此您会收到错误消息。另一种解决方案是使用赋值:

X::X()
{
    a = new Y(); // or a = boost::make_shared<Y>()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多