Explicit copy constructor compilation error

I checked the operator overload in C ++ and came across something I did not expect, and I have some doubts.

My copy constructor is declared and implemented as

explicit Vector(const Vector& v); Vector::Vector(const Vector& v) : _x(v._x), _y(v._y), _z(v._z) {} 

then I overload compound assignment operators

 Vector Vector::operator+(const Vector& v) const { Vector tmp(*this); tmp += v; return tmp; } Vector Vector::operator-(const Vector& v) const { Vector tmp(*this); tmp -= v; return tmp; } 

however, in the return I received the error message no matching constructor for initialization of 'Vector' .

Since the only thing I added to my constructor is the explicit keyword, I deleted it and the code compiles just fine, why?

I also tested new things from C ++ 11 and found that I could declare my constructor as a moving constructor

 explicit Vector(const Vector&& v); 

and the code compiles just fine. If I do this, do I need to have both copy and move constructors?

 explicit Vector(const Vector& v); explicit Vector(const Vector&& v); 

or just having a move constructor will work fine? If I want to stick with C ++ 11, what is the right approach?

+6
source share
2 answers

You have defined an explicit copy constructor, but functions

 Vector Vector::operator+(const Vector& v) const 

and

 Vector Vector::operator-(const Vector& v) const 

should return by value and can no longer, due to explicit (in other words, they cannot copy tmp to the returned object).

I also tested new things from C ++ 11 and found that I could declare my constructor as a moving constructor explicit Vector(const Vector&& v); , and the code compiles just fine. If I do this, do I need to have both copy and move constructors?

Not sure if I understand what you mean here. You will have the same problem if you only declare an explicit move constructor (which prevents the compiler from generating a default copy constructor). I cannot create "compiled" code.

+5
source

Returning an object by value requires an implicit copy construct. Creating an explicit instance constructor prevents this.

This is true whether the compiler chooses not to use the copy constructor (for example, optimizing the return value).

0
source

Source: https://habr.com/ru/post/984744/


All Articles