移动构造函数(错误:调用隐式删除的复制构造函数)

Move constructor (error: call to implicitly-deleted copy constructor)

本文关键字:构造函数 删除 复制 调用 错误 移动      更新时间:2023-10-16

我第一次尝试移动构造函数和移动赋值运算符,但是当我使用 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 值引用,以便它可以由移动构造函数/移动赋值使用。

相关文章: