[英]Move constructor (error: call to implicitly-deleted copy constructor)
I am experimenting for the first time with the move constructor and the move assignment operator but when I compile using clang++: 我第一次尝试使用move构造函数和move赋值运算符,但是当我使用clang ++进行编译时:
c++ -o image -O3 image.cpp -std=c++0x -stdlib=libc++
I get the following error message: 我收到以下错误消息:
image.cpp:125:11: error: call to implicitly-deleted copy constructor of 'Image'
Image res = sample;
I really don't understand what that means and how to fix this? 我真的不明白这意味着什么以及如何解决这个问题? I copied the entire code. 我复制了整个代码。 Any help would be greatly appreciated. 任何帮助将不胜感激。
PS: I looked on the web and couldn't find anything about this error message (apart some post from 2011/2012 relative to a bug in clang++ which I believe would have been fixed by then). 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 default\n");
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;
}
According to the C++ Standard 根据C ++标准
If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; 如果类定义声明了move构造函数或move赋值运算符,则隐式声明的copy构造函数将定义为delete; otherwise, it is defined as defaulted 否则,它定义为默认值
That your example would work try the following 您的示例可以尝试以下操作
Image res = std::move( sample );
Well as the message says - the image class doesn't have a copy constructor. 就像消息说的那样-图像类没有复制构造函数。 So you can either implement one or if your intention was to test move constructor try this: 因此,您可以实现一个,或者如果您打算测试move构造函数,请尝试以下操作:
int main(int argc, char **argv)
{
Image sample;// = readPPM("./lean.ppm");
Image res = std::move(sample);
return 0;
}
std::move
will cast the sample
to r-value reference, so that it can be used by move-constructor/move-assignment. std::move
会将sample
为r值参考,以便可以由move-constructor / move-assignment使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.