【问题标题】:Trouble constructing shared_ptr构造 shared_ptr 时遇到问题
【发布时间】:2013-08-25 21:06:29
【问题描述】:

我是智能指针的新手,我正在解决每一个绊脚石。

我有一个结构 texture_t:

struct texture_t
{
    hash32_t hash;
    uint32_t width;
    uint32_t height;
    uint32_t handle;
};

当我尝试使用此行创建此结构的 shared_ptr 时:

auto texture_shared_ptr = std::make_shared<texture_t>(new texture_t());

我收到此错误:

error C2664: 'mandala::texture_t::texture_t(const mandala::texture_t &)' : cannot convert parameter 1 from 'mandala::texture_t *' to 'const mandala::texture_t &'

这个错误来自哪里,我该如何避免它?

【问题讨论】:

    标签: c++ shared-ptr make-shared


    【解决方案1】:

    std::make_shared&lt;T&gt;(args...) 的重点是分配一个T 以参数args... 构造的对象。这个操作背后的想法是std::shared_ptr&lt;T&gt; 在概念上维护了两个分配的对象:

    1. 指向T 类型的指针。
    2. 跟踪当前std::shared_pt&lt;T&gt; 数量和引用该对象的std::weak_ptr&lt;T&gt; 对象数量的记录。

    在构造std::shared_ptr&lt;T&gt; 时,构造函数会进行第二次分配以构造记录以用于其内部簿记。 std:make_shared&lt;T&gt;(args...) 只分配一次内存。

    您看到的错误是由于尝试使用mandala::texture_t* 构造mandala::texture_t 而导致的,但mandala::texture_t 的唯一一个参数构造函数是复制构造函数。但是,指针不符合复制构造函数的参数。

    【讨论】:

      【解决方案2】:

      您不应该将newed 指针传递给std::make_shared。您只需要传递参数即可构造texture_t

      【讨论】:

      • 像魅力一样工作,谢谢。看起来这些东西比我想象的要聪明!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多