相关疑难解决方法(0)

2753
推荐指数
11
解决办法
81万
查看次数

尝试创建shared_ptr时std :: make_shared()中的错误?

(使用Visual Studio 2010)我正在尝试在我的项目中创建现有类的shared_ptr(类是在std :: shared_ptr存在之前写的十年).该类采用非const指针指向另一个对象,它的空参数构造函数是私有的.

class Foobar {
public:
    Foobar(Baz* rBaz);

private:
    Foobar();
}
Run Code Online (Sandbox Code Playgroud)

当我尝试创建一个shared_ptr时,事情进展不顺利:

Baz* myBaz = new Baz();
std::shared_ptr<Foobar> sharedFoo = std::make_shared<Foobar>(new Foobar(myBaz));
Run Code Online (Sandbox Code Playgroud)

在VS2010上,这给了我

error C2664: 'Foobar::Foobar(const Foobar &)' : cannot convert parameter 1 from 'Foobar *' to 'const Foobar &'
3>          Reason: cannot convert from 'Foobar *' to 'const Foobar'
Run Code Online (Sandbox Code Playgroud)

由于某种原因,它似乎是调用复制构造函数Foobar而不是构造函数Baz*.

我也不确定这个cannot convert from 'Foobar *' to 'const Foobar'部分.我最好的解释是我的模板类型shared_ptr<Foobar>是错误的.我做了,shared_ptr<Foobar*>但这似乎是错的,我见过的所有例子都没有使该类型成为原始指针.

似乎shared_ptr<Foobar*>正确地编译所有内容,但是Foobar当所有内容shared_ptr都超出范围时,是否会阻止对象被正确删除?

编辑: …

c++ shared-ptr visual-c++-2010 make-shared c++11

6
推荐指数
1
解决办法
1万
查看次数

如何克服make_shared constness

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

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

#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提前!

c++ boost shared-ptr

5
推荐指数
1
解决办法
1962
查看次数