这是我的网格物体类
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/