(使用 Visual Studio 2010)我试图在我的项目中创建一个现有类的 shared_ptr(类是在 std::shared_ptr 存在十年之前编写的)。这个类接受一个指向另一个对象的非常量指针,它的空参数构造函数是私有(private)的。
class Foobar {
public:
Foobar(Baz* rBaz);
private:
Foobar();
}
当我尝试为它创建一个 shared_ptr 时,事情并不顺利:
Baz* myBaz = new Baz();
std::shared_ptr<Foobar> sharedFoo = std::make_shared<Foobar>(new Foobar(myBaz));
在 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'
出于某种原因,它似乎正在调用 Foobar
的复制构造函数而不是采用 Baz*
的构造函数.
我也不确定 cannot convert from 'Foobar *' to 'const Foobar'
部分。我最好的解释是我的模板类型 shared_ptr<Foobar>
是错的。我做到了shared_ptr<Foobar*>
但这似乎是错误的,我见过的所有示例都没有使类型成为原始指针。
似乎使一切shared_ptr<Foobar*>
编译正确,但会阻止 Foobar
当所有 shared_ptr
时对象被正确删除超出范围了吗?
编辑: 这似乎相关,但我没有使用 Boost:boost make_shared takes in a const reference. Any way to get around this?
Edit2:为了清楚起见,如果您想知道我为什么使用 make_shared()
,在我的实际代码中 sharedFoo
变量是第三类的类成员(独立于 Foobar
和 Baz
)。
最佳答案
应该是这样;
std::shared_ptr<Foobar> sharedFoo = std::make_shared<Foobar>(myBaz);
...因为 make_shared 通过运行构造函数为您构造实际对象。
关于c++ - 尝试创建 shared_ptr 时 std::make_shared() 出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39050718/