如何克服make_shared constness

soh*_*hel 5 c++ boost shared-ptr

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

以下是用于说明的代码示例:

#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));

}
Run Code Online (Sandbox Code Playgroud)

问题是我无法创建shared_ptr实例,因为make_shared获取并将TestClass构造函数的参数下传为"const A1&,const A2&,...",如下所示:

template<typename T, typename Arg1, typename Arg2 >
    shared_ptr<T> make_shared( Arg1 const & arg1, Arg2 const & arg2 );
Run Code Online (Sandbox Code Playgroud)

我可以用boost :: shared(new ...)或用于const引用的重写构造函数进行欺骗,但似乎不是应该的方式.

Thnx提前!

Yli*_*sar 11

你可以boost::ref用来包装参数,即:

ptr = boost::make_shared< TestClass >( boost::ref( c ), c );
Run Code Online (Sandbox Code Playgroud)