移动构造函数(错误:调用隐式删除的复制构造函数)
Move constructor (error: call to implicitly-deleted copy constructor)
我第一次尝试移动构造函数和移动赋值运算符,但是当我使用 clang++ 编译时:
c++ -o image -O3 image.cpp -std=c++0x -stdlib=libc++
我收到以下错误消息:
image.cpp:125:11: error: call to implicitly-deleted copy constructor of 'Image'
Image res = sample;
我真的不明白这意味着什么以及如何解决这个问题?我复制了整个代码。任何帮助将不胜感激。
PS:我在网上查看了一下,找不到有关此错误消息的任何内容(除了 2011/2012 中与 clang++ 中的错误相关的一些帖子,我相信那时会修复该错误)。
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <fstream>
#include <cassert>
class Image
{
public:
Image() : w(512), h(512), d(NULL)
{
//printf("constructor defaultn");
d = new float[w * h * 3];
memset(d, 0x0, sizeof(float) * w * h * 3);
}
Image(const unsigned int &_w, const unsigned int &_h) : w(_w), h(_h), d(NULL)
{
d = new float[w * h * 3];
memset(d, 0x0, sizeof(float) * w * h * 3);
}
// move constructor
Image(Image &&img) : w(0), h(0), d(NULL)
{
w = img.w;
h = img.h;
d = img.d;
img.d = NULL;
img.w = img.h = 0;
}
// move assignment operator
Image& operator = (Image &&img)
{
if (this != &img) {
if (d != NULL) delete [] d;
w = img.w, h = img.h;
d = img.d;
img.d = NULL;
img.w = img.h = 0;
}
return *this;
}
//~Image() { if (d != NULL) delete [] d; }
unsigned int w, h;
float *d;
};
int main(int argc, char **argv)
{
Image sample;// = readPPM("./lean.ppm");
Image res = sample;
return 0;
}
根据C++标准
如果类定义声明了移动构造函数或移动赋值 运算符,隐式声明的复制构造函数定义为 删除;否则,它被定义为默认值
为了使您的示例有效,请尝试以下操作
Image res = std::move( sample );
正如
消息所说 - 图像类没有复制构造函数。因此,您可以实现一个,或者如果您打算测试移动构造函数,请尝试以下操作:
int main(int argc, char **argv)
{
Image sample;// = readPPM("./lean.ppm");
Image res = std::move(sample);
return 0;
}
std::move
会将sample
强制转换为 r 值引用,以便它可以由移动构造函数/移动赋值使用。
相关文章:
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- std::ofstream 作为类成员删除复制构造函数?
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- C++ 尝试在不存在的构造函数中引用已删除的函数(使用 rapidJson)
- 具有已删除移动和复制构造函数的类的就地构造
- 聚合初始化和删除的复制构造函数,也称为不可复制的 obejcts 作为字段
- 在引用初始化中使用已删除的复制构造函数进行复制初始化
- 在运行时有条件地删除类成员或跳过调用该成员对象的构造函数
- 我的类中几乎所有的构造函数和解构函数都被隐式定义为已删除?
- 为什么在删除"移动构造函数"时使用"复制构造函数"?
- 调用类模板中隐式删除的复制构造函数
- 当类型适当的构造函数可用时,为什么一个编译器尝试使用已删除的副本构造函数
- 编译器在C++中调用另一个函数时,在参数中查找已删除的构造函数
- 在构造函数中删除后继续执行
- 删除了在初始值设定项中调用的构造函数
- 删除使数据处于"错误状态"的默认构造函数的模式?
- C ++(为什么)确实移动构造函数删除运算符=
- 仅仅以避免隐式复制构造函数删除,使用shared_ptr而不是unique_ptr作为类成员明智