我遇到了一个问题,无法决定正确的解决方案是什么。
下面是用于说明的代码示例:
#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&, const A2&,...
传递给 TestClass 构造函数,如文档所述:
template<typename T, typename Arg1, typename Arg2 >
shared_ptr<T> make_shared( Arg1 const & arg1, Arg2 const & arg2 );
我可以用 boost::shared(new ...)
来欺骗它,或者为 const
引用重写构造函数,但这似乎不是正确的解决方案.
提前致谢!
最佳答案
您可以使用 boost::ref
来包装参数,即:
ptr = boost::make_shared< TestClass >( boost::ref( c ), c );
关于c++ - 如何克服 make_shared constness,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11742491/