尝试制作shared_ptr时std :: make_shared()中出现错误? [英] Errors in std::make_shared() when trying to make shared_ptr?
问题描述
(使用Visual Studio 2010)我正在尝试在项目中创建一个现有类的shared_ptr(该类是在std :: shared_ptr存在十年之前编写的)。此类使用非常量指针指向另一个对象,它的空参数构造函数是私有的。
(Using Visual Studio 2010) I'm trying to create a shared_ptr of an existing class in my project (class was written a decade before std::shared_ptr existed). This class takes a non-const pointer to another object, it's empty parameter constructor is private.
class Foobar {
public:
Foobar(Baz* rBaz);
private:
Foobar();
}
当我尝试为其创建一个shared_ptr时,事情进展不顺利:
When I try to create a shared_ptr to it, things don't go well:
Baz* myBaz = new Baz();
std::shared_ptr<Foobar> sharedFoo = std::make_shared<Foobar>(new Foobar(myBaz));
在VS2010上,这给了我
On VS2010, this gives me
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 *
的构造函数。
For some reason it appears to be calling the copy constructor of Foobar
instead of the constructor that takes a Baz*
.
我也不确定无法从 Foobar *转换为 const Foobar
部分。我最好的解释是 shared_ptr< Foobar>
的模板类型是错误的。我将其设置为 shared_ptr< Foobar *>
,但这似乎是错误的,我见过的所有示例都没有将类型设为原始指针。
I'm also not sure about the cannot convert from 'Foobar *' to 'const Foobar'
part. My best interpretation is that my templated-type of shared_ptr<Foobar>
is wrong. I made it shared_ptr<Foobar*>
but this seems wrong, all examples I've seen don't make the type a raw pointer.
似乎可以使所有 shared_ptr< Foobar *>
正确编译,但这会阻止 Foobar
对象是否在所有 shared_ptr
都超出范围时被正确删除?
It seems that making everything shared_ptr<Foobar*>
compiles properly, but will that prevent the Foobar
object from getting deleted properly when all shared_ptr
's go out of scope?
This seems related, but I'm not using Boost: boost make_shared takes in a const reference. Any way to get around this?
Edit2:为清楚起见,如果您想知道为什么我使用 make_shared()
,在我的实际代码中, sharedFoo
变量是第三类的类成员(独立于 Foobar
和 Baz
)。
For clarity, if you're wondering why I'm using make_shared()
, in my actual code the sharedFoo
variable is a class member of a third class (independent of Foobar
and Baz
).
推荐答案
应该是;
std::shared_ptr<Foobar> sharedFoo = std::make_shared<Foobar>(myBaz);
...因为make_shared通过运行构造函数为您构造了实际对象。
...since make_shared constructs the actual object for you by running the constructor.
这篇关于尝试制作shared_ptr时std :: make_shared()中出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!