【问题标题】:C++ Implicit deletion of class using unique pointerC++ 使用唯一指针隐式删除类
【发布时间】:2017-05-19 10:43:50
【问题描述】:

我正在尝试为包含指向某个无符号字符数组的唯一指针的类创建一个复制赋值运算符。

这是它的样子:

// 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&lt;unsigned char[]&gt; data;

非常感谢!

【问题讨论】:

  • Rule of Five! (IOW,你还需要一个 copy-ctor)。另请查看make_unique
  • 不是答案,但我认为您也需要增加其他迭代器:img_beg。或者只使用std::copy
  • 你所拥有的是不是一个赋值,它是一个初始化,所以它调用复制构造函数
  • 也不需要data.reset(),当你将assign移动到unique_ptr时会发生这种情况(这就是它“智能”的原因)。
  • 使用 std::vector 并且您不必编写任何复制代码。

标签: c++ pointers unique


【解决方案1】:

当你有

Image copy = img;

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

Image copy;
copy = img;

这将调用复制赋值运算符。

【讨论】:

  • 谢谢,我想知道为什么第二种方法有效,但第一种方法无效。
  • @MattYoung 没问题。很高兴能提供帮助。
猜你喜欢
  • 1970-01-01
  • 2021-06-14
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 2011-04-30
  • 2010-09-08
  • 1970-01-01
相关资源
最近更新 更多