在构造函数中使用引用创建 boost::shared_ptr
create boost::shared_ptr with a reference in constructor
我有以下情况:class "B" 继承自 class "A"。 class "C" 有一个对 "A" 的引用,它在构造函数中传递给了它。在class"D"中,我想使用class"C",但我只有"B"的引用。目前我正在使用标准指针,但我需要迁移到 boost::shared_ptr.
class A {...};
class B: public A {...};
class C {
public:
C(A& _a)
: a(_a)
{...}
private:
A& a;
};
class D
{
private:
B& b;
void someFunc()
{
C* c1 = new C(b); // Working
boost::shared_ptr<C> c2 = boost::make_shared<C>(b); // not working: "cannot convert const B in A&" error
}
};
我的问题:我如何需要 wrap/cast/derefrence/whatever 实例 "b",以便正确创建 shared_ptr?
通过上面的实现,我得到一个 "cannot convert const B in A&" 错误。
感谢您的支持。
自己找到了解决方案:我需要将其包装在 boost::ref 中,即
boost::shared_ptr<C> c2 = boost::make_shared<C>(boost::ref(b));
我有以下情况:class "B" 继承自 class "A"。 class "C" 有一个对 "A" 的引用,它在构造函数中传递给了它。在class"D"中,我想使用class"C",但我只有"B"的引用。目前我正在使用标准指针,但我需要迁移到 boost::shared_ptr.
class A {...};
class B: public A {...};
class C {
public:
C(A& _a)
: a(_a)
{...}
private:
A& a;
};
class D
{
private:
B& b;
void someFunc()
{
C* c1 = new C(b); // Working
boost::shared_ptr<C> c2 = boost::make_shared<C>(b); // not working: "cannot convert const B in A&" error
}
};
我的问题:我如何需要 wrap/cast/derefrence/whatever 实例 "b",以便正确创建 shared_ptr?
通过上面的实现,我得到一个 "cannot convert const B in A&" 错误。
感谢您的支持。
自己找到了解决方案:我需要将其包装在 boost::ref 中,即
boost::shared_ptr<C> c2 = boost::make_shared<C>(boost::ref(b));