Matt Young
Matt Young

Reputation: 73

C++ Implicit deletion of class using unique pointer

I'm trying to create a copy-assignment operator for a class containing a unique pointer to some unsigned char array.

Here is what it looks like:

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

But I am getting the following error thrown in console:

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

I am trying to create an Image object in a driver file as follows:

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

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

... and the image stores the pointer std::unique_ptr<unsigned char[]> data;

Many thanks!

Upvotes: 1

Views: 934

Answers (1)

NathanOliver
NathanOliver

Reputation: 180500

When you have

Image copy = img;

You are not calling the copy assignment operator. Image copy is a declaration so you are initializing which means you are calling a copy constructor. That means you also need to defined a copy constructor for your class. You could, if you do not want to provide one and if Image is default constructable do

Image copy;
copy = img;

Which will call the copy assignment operator.

Upvotes: 3

Related Questions