【问题标题】:Errors in std::make_shared() when trying to make shared_ptr?尝试制作Shared_ptr时,std :: make_shared()错误?
【发布时间】:2016-12-27 07:17:50
【问题描述】:

(使用 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 的复制构造函数,而不是采用Baz* 的构造函数。

我也不确定cannot convert from 'Foobar *' to 'const Foobar' 部分。我最好的解释是我的shared_ptr&lt;Foobar&gt; 模板类型是错误的。我做到了shared_ptr&lt;Foobar*&gt;,但这似乎是错误的,我见过的所有示例都没有将类型设为原始指针。

似乎使 shared_ptr&lt;Foobar*&gt; 的所有内容都能正确编译,但是当所有 shared_ptr 超出范围时,这是否会阻止 Foobar 对象被正确删除?

编辑:这似乎相关,但我没有使用 Boost:boost make_shared takes in a const reference. Any way to get around this?

Edit2:为了清楚起见,如果您想知道我为什么使用make_shared(),在我的实际代码中,sharedFoo 变量是第三类的类成员(独立于 @ 987654335@ 和 Baz)。

【问题讨论】:

  • 我无法测试 atm,但不应该这样; std::shared_ptr sharedFoo = std::make_shared(myBaz);
  • 啊!这成功了……显然make_shared() 为您调用模板类型的构造函数,所以我不应该传入new'ed 对象。谢谢!再说一遍作为答案,我会将其标记为正确。
  • 完成,在能够自己测试之后:)

标签: c++ c++11 shared-ptr visual-c++-2010 make-shared


【解决方案1】:

应该是这样的;

std::shared_ptr<Foobar> sharedFoo = std::make_shared<Foobar>(myBaz);

...因为 make_shared 通过运行构造函数为您构造实际对象。

【讨论】:

    猜你喜欢
    • 2012-02-06
    • 2014-08-10
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多