【问题标题】:how to overcome make_shared constness如何克服 make_shared 常量
【发布时间】:2023-03-31 16:01:01
【问题描述】:

我遇到了一个问题,无法确定正确的解决方案是什么。

下面是示例代码:

#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>

class TestClass{
    public:
        int a;
        TestClass(int& a,int b){};
    private:
        TestClass();
        TestClass(const TestClass& rhs);
};

int main(){
    int c=4;
    boost::shared_ptr<TestClass> ptr;

//NOTE:two step initialization of shared ptr    

//     ptr=boost::make_shared<TestClass>(c,c);// <--- Here is the problem
    ptr=boost::shared_ptr<TestClass>(new TestClass(c,c));

}

问题是我无法创建 shared_ptr 实例,因为 make_shared 获取并将参数作为 const A1&amp;, const A2&amp;,... 传递给 TestClass 构造函数,如文档所述:

template<typename T, typename Arg1, typename Arg2 >
    shared_ptr<T> make_shared( Arg1 const & arg1, Arg2 const & arg2 );

我可以用boost::shared(new ...) 欺骗它或重写const 引用的构造函数,但这似乎不是正确的解决方案。

提前谢谢你!

【问题讨论】:

标签: c++ boost shared-ptr


【解决方案1】:

您可以使用boost::ref 将参数包装起来,即:

ptr = boost::make_shared< TestClass >( boost::ref( c ), c );

【讨论】:

  • 非常感谢!我将通过 hart 了解 boost doc 的和平:)
猜你喜欢
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多