构造shared_ptr时出现问题

Trouble constructing shared_ptr

本文关键字:问题 ptr shared 构造      更新时间:2023-10-16

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

我有一个结构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 &'

这个错误是从哪里来的?我该如何避免它?

std::make_shared<T>(args...)的目的是分配一个用参数args...构造的T对象。此操作背后的思想是std::shared_ptr<T>在概念上维护两个分配的对象:

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

当构造std::shared_ptr<T>时,构造函数进行第二次分配来构造用于其内部记账的记录。std:make_shared<T>(args...)只进行一次内存分配。

您看到的错误源于尝试使用mandala::texture_t*构造mandala::texture_t,但mandala::texture_t只有一个参数构造函数是复制构造函数。但是,指针不能作为复制构造函数的参数。

不应该将new ed指针传递给std::make_shared。您只需要传递参数,就可以从中构造texture_t