c++ - 如何克服 make_shared constness

标签 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));

}

问题是我无法创建 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/

相关文章:

c++ - RobuSTLy 找到 N 个直径相同的圆 : alternative to bruteforcing Hough transform threshold

c++ - 如果变体之一没有特定字段,则无法访问该变体

python - Boost Python,Visual Studio 不创建 DLL

c++ - 为什么在使用线程池时对 boost::async 的嵌套调用会阻塞?

c++ - 从中创建 shared_ptr 后删除原始指针

c++ - 将 double 转换为固定宽度的字符串

c++ - 最后一个 return *this c++ 会发生什么?

c++ - 如何创建具有 64 位输出的良好 hash_combine(受 boost::hash_combine 启发)

boost::smart_ptr 的 C++ 非侵入式 boost 序列化

c++ - 在 Visual C++ 2010 上哪个更快 - std::shared_ptr 或 boost::shared_ptr?