【问题标题】:create boost::shared_ptr with a reference in constructor使用构造函数中的引用创建 boost::shared_ptr
【发布时间】:2016-03-04 09:48:19
【问题描述】:

我有以下情况:类“B”继承自类“A”。类“C”具有对“A”的引用,该引用在构造函数中传递给。在“D”类中,我想使用“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
   }
};

我的问题:我需要如何包装/投射/取消引用/无论实例“b”,以便正确创建 shared_ptr?

通过上面的实现,我得到一个“无法在 A& 中转换 const B”错误。

感谢您的支持。

【问题讨论】:

  • 这是在 C++03 上下文中吗?如果是这样,请相应地标记。我希望您的代码能够在 C++11 中开箱即用。
  • 测试过;它适用于 C++11 和 with C++14。
  • 始终包含实际的编译器错误消息。 "// not working" 非常搞笑

标签: boost shared-ptr c++03


【解决方案1】:

自己找到了解决方案:我需要将它包装在 boost::ref 中,即

boost::shared_ptr<C> c2 = boost::make_shared<C>(boost::ref(b));

【讨论】:

  • 你没有抓住重点。这是关于我的样品的。现在 +1(我修复了你的问题标签)
猜你喜欢
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多