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