尝试创建shared_ptr时std::make_shared()中出现错误?
(使用 Visual Studio 2010)我试图在我的项目中创建现有类的shared_ptr(类是在 std::shared_ptr 存在之前十年编写的)。该类采用一个指向另一个对象的非常量指针,它的空参数构造函数是私有的。
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
的复制构造函数,而不是调用采用a的构造函数巴兹*。
我也不确定 无法从 'Foobar *' 转换为 'const Foobar'
部分。我最好的解释是我的 shared_ptr
模板类型是错误的。我将其设为 shared_ptr
但这似乎是错误的,我见过的所有示例都没有使该类型成为原始指针。
似乎使所有 shared_ptr
都能正确编译,但是当所有 shared_ptr
' 时,这会阻止 Foobar
对象被正确删除吗?超出范围了吗?
编辑:这似乎相关,但我没有使用Boost:boost make_shared 接受 const 引用。有什么方法可以解决这个问题吗?
编辑2:为了清楚起见,如果您想知道为什么我使用 make_shared()
,在我的实际代码中 < code>sharedFoo 变量是第三个类的类成员(独立于 Foobar
和 Baz
)。
(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();
}
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));
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'
For some reason it appears to be calling the copy constructor of Foobar
instead of the constructor that takes a Baz*
.
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.
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?
Edit: This seems related, but I'm not using Boost: boost make_shared takes in a const reference. 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
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
应该是这样;
...因为 make_shared 通过运行构造函数来为您构造实际的对象。
That should be;
...since make_shared constructs the actual object for you by running the constructor.