Reputation: 981
Basically, the argument of the move constructor is the class itself.
However, if I want to construct an object of the class from a lvalue without copy operation can I do like this?
class A{
A(const LargeDataType& inData):data(inData) {} // constructor 1
A(LargeDataType&& inData):data(std::move(inData)) {} // constructor 2
private:
LargeDataType data;
};
To use it:
Method 1:
LargeDataType outData = 100;
A objA(std::move(outData)); // call constructor 2
Method 2 (If constructor 2 was not implemented):
LargeDataType outData = 100;
A objA(std::move(outData)); // call constructor 1
In this way, there is no copy operation when constructing the objA. My questions are:
Is this legal to create a move constructor like this?
This is more efficient than traditional constructor because no copy needed during objA creation?
Whether method 2 could be better and has the same efficiency as the method 1?
Thanks a lot!
Upvotes: 1
Views: 515
Reputation: 206717
What you have is not a move constructor. It is just a constructor that takes rvalue references as arguments. The are perfectly fine constructors but they are not move constructors.
From the C++11 Standard (12.8/3):
A non-template constructor for class
X
is a move constructor if its first parameter is of typeX&&
,const X&&
,volatile X&&
, orconst volatile X&&
, and either there are no other parameters or else all other parameters have default arguments (8.3.6).
Only
A(A&& a) { ... }
A(const A&& a) { ... }
A(volatile A&& a) { ... }
A(volatile const A&& a) { ... }
maybe called move constructors.
If you have parameters with default values in addition to the above, they also qualify as move constructors. E.g.
A(A&& a, T arg = {}) { ... }
Upvotes: 2