c++ - 我如何使用移动语义从类对象中创建共享指针

标签 c++

这是我的网格物体类

struct texture
{
    std::string textureName;
    unsigned int textureId;
};

class Mesh
{
public:
    /* Mesh data */
    std::vector<texture> textures;
    
    /* Functions */
    Mesh(std::vector<texture> &text);
    Mesh(const Mesh& mesh) = delete;
    Mesh& operator = (const Mesh& mesh) = delete;
    Mesh(Mesh &&other);
    Mesh& operator=(Mesh &&other);
    ~Mesh();        

};




 #include "Mesh.h"

Mesh::Mesh(std::vector<texture> &text) : textures(text)
{
}

Mesh::Mesh(Mesh &&other) : textures( other.textures)
{
    for (auto &tex : other.textures)
        tex.textureId = 0;
}

Mesh& Mesh::operator=(Mesh &&other)
{
    if (this != &other)
    {
        textures = other.textures;
    }

    for (auto &tex : other.textures)
        tex.textureId = 0;

    return *this;
}

Mesh::~Mesh()
{
    for (auto &tex : textures)
        glDeleteTextures(1, &tex.id);
}
现在我意识到我需要为该类对象创建一个共享指针,但是当我尝试这样做时,尝试引用已删除的函数会给我带来错误,我认为这是因为我正在使用move语义。
std::vector< texture> textures;
    Mesh m(textures);
    std::shared_ptr<Mesh> myMesh = std::make_shared<Mesh>(m);
是否可以使用move语义从类对象中创建共享指针?
错误信息
错误C2280'Mesh::Mesh(const Mesh&)':尝试引用已删除的函数

最佳答案

如果添加了移动构造函数,则会默认删除默认的复制构造函数,并且std::make_shared<Mesh>(m)使用该复制构造函数。这就是为什么您会收到如下错误消息的原因:

error: use of deleted function 'constexpr Mesh::Mesh(const Mesh&)'
            -> decltype(::new((void*)0) _Tp(std::declval<_Args>()...))

note: 'constexpr Mesh::Mesh(const Mesh&)' is implicitly declared as deleted 
          because 'Mesh' declares a move constructor or move assignment operator
如果您确实要移动,则需要使用std::move:
Mesh m(textures);
std::shared_ptr<Mesh> myMesh = std::make_shared<Mesh>(std::move(m));
但是对于所示的代码,尚不清楚您为什么要进行移动,因为您似乎没有将m用于其他任何内容。

关于c++ - 我如何使用移动语义从类对象中创建共享指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62859934/

相关文章:

c++ - Linux 有更快的 c++ 编译器吗?

c++ - 即使包含库也无法将 curlpp 与 Xcode 一起使用

c++ - 如何实现自定义模板排序功能?

c++ - 尽管文件指针正确,但 fclose() 期间出现段错误

c++ - 相同代码中的不一致行为

c++ - qt错误: multiple definition of `Protocol::Protocol()'

C++地址字符串->长

c++ - 如何在 MFC(或仅 C++)中将表格写入剪贴板以粘贴到 Word 中?

c++ - QLabel 自动缩放

c++ - 从通过指针取消引用从 C 函数调用的 C++ 函数中抛出