[英]Errors in std::make_shared() when trying to make 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). (使用Visual Studio 2010)我正在尝试在项目中创建一个现有类的shared_ptr(该类是在std :: shared_ptr存在十年之前编写的)。 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();
}
When I try to create a shared_ptr to it, things don't go well: 当我尝试为其创建一个shared_ptr时,事情进展不顺利:
Baz* myBaz = new Baz();
std::shared_ptr<Foobar> sharedFoo = std::make_shared<Foobar>(new Foobar(myBaz));
On VS2010, this gives me 在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'
For some reason it appears to be calling the copy constructor of Foobar
instead of the constructor that takes a Baz*
. 由于某种原因,它似乎正在调用
Foobar
的副本构造函数,而不是采用Baz*
的构造函数。
I'm also not sure about the cannot convert from 'Foobar *' to 'const Foobar'
part. 我也不确定
cannot convert from 'Foobar *' to 'const Foobar'
部分。 My best interpretation is that my templated-type of shared_ptr<Foobar>
is wrong. 我最好的解释是我的
shared_ptr<Foobar>
模板类型是错误的。 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*>
但这似乎是错误的,我看到的所有示例都没有将类型设为原始指针。
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? 似乎使所有
shared_ptr<Foobar*>
都能正确编译,但是当所有shared_ptr
超出范围时,这是否会阻止Foobar
对象被正确删除?
Edit: This seems related, but I'm not using Boost: boost make_shared takes in a const reference. 编辑:这似乎有关,但我没有使用Boost: boost make_shared接受const引用。 Any way to get around this?
有什么办法解决这个问题?
Edit2: 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
). Edit2:为清楚起见,如果您想知道为什么我使用
make_shared()
,那么在我的实际代码中, sharedFoo
变量是第三类的类成员(独立于Foobar
和Baz
)。
That should be; 那应该是;
std::shared_ptr<Foobar> sharedFoo = std::make_shared<Foobar>(myBaz);
...since make_shared constructs the actual object for you by running the constructor. ...因为make_shared通过运行构造函数为您构造了实际对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.