gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:25:32 24 4
gpt4 key购买 nike

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

这是它的样子:

// 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;

非常感谢!

最佳答案

当你有

Image copy = img;

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

Image copy;
copy = img;

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

关于C++使用唯一指针隐式删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44068008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com