C ++使用唯一指针隐式删除类

时间:2017-05-19 10:43:50

标签: c++ pointers unique

我试图为包含指向某个unsigned char数组的唯一指针的类创建一个复制赋值运算符。

这是它的样子:

// equals operator
        Image & operator=(const Image & rhs) {
            if(data != nullptr) {
                data.reset();
            }

            data = std::unique_ptr<unsigned char[]>(new unsigned char[rhs.width * rhs.height]);
            Image::iterator beg = this->begin();
            Image::iterator end = this->end();
            Image::iterator img_beg = rhs.begin();
            Image::iterator img_end = rhs.end();

            while(beg != end) {
                *beg = *img_beg;
                ++beg;
            }

            width = rhs.width;
            height = rhs.height;
            return *this;
        }

但是我在控制台中抛出了以下错误:

imageops.cpp: In function ‘void handleInput(int, char**)’:
imageops.cpp:26:16: error: use of deleted function 
‘YNGMAT005::Image::Image(const YNGMAT005::Image&)’
Image copy = img;
            ^~~
In file included from imageops.cpp:6:0:
image.h:14:8: note: ‘YNGMAT005::Image::Image(const YNGMAT005::Image&)’ 
is implicitly deleted because the default definition would be ill-
formed:
class Image {
    ^~~~~
image.h:14:8: error: use of deleted function ‘std::unique_ptr<_Tp [], 
_Dp>::unique_ptr(const std::unique_ptr<_Tp [], _Dp>&) [with _Tp = 
unsigned char; _Dp = std::default_delete<unsigned char []>]’
In file included from /usr/include/c++/6/memory:81:0,
             from image.h:7,
             from imageops.cpp:6:
/usr/include/c++/6/bits/unique_ptr.h:633:7: note: declared here
   unique_ptr(const unique_ptr&) = delete;
   ^~~~~~~~~~
makefile:5: recipe for target 'imageops.o' failed
make: *** [imageops.o] Error 1

我正在尝试在驱动程序文件中创建一个Image对象,如下所示:

Image img;
    string flag = cmds.at(1);
    img.load(cmds.at(2));

    //cout << img;
    Image copy = img;

...图像存储指针std::unique_ptr<unsigned char[]> data;

非常感谢!

1 个答案:

答案 0 :(得分:3)

当你有

Image copy = img;

您没有调用复制赋值运算符。 Image copy是一个声明,因此您正在初始化,这意味着您正在调用复制构造函数。这意味着您还需要为您的类定义一个复制构造函数。你可以,如果你不想提供一个,Image是默认可构造的

Image copy;
copy = img;

将调用复制赋值运算符。