Reputation: 61
I would like to know when move constructor are called in C++ code.
It means, I know that when I call Foo a(b)
it is copy constructor, so what have I to code to call move constructor.
Upvotes: 5
Views: 485
Reputation: 3381
In general we have to tell it by giving an rvalue
reference argument. For example:
template<class T>
void swap(T& a, T& b)
{
T tmp = std::move(a);
a = std::move(b);
b = std::move(tmp);
}
The move()
is a standard-library function returning an rvalue reference to its argument
move(x)
means "give me an rvalue reference to x". That is, std::move(x)
does not move anything, instead, it allows a user to move x.
Source: The C++ Programming Language (B. Stroustrup)
Upvotes: 3
Reputation: 110648
A move constructor is just another constructor. If you have overloaded constructors, just like having any other functions overloaded, the choice of which constructor is called comes down to the rules of overload resolution. That is, when you construct an object with Foo a(<some-expression>);
, there might be multiple possible constructors and one needs to be chosen.
The copy constructor takes one argument of type const Foo&
. This lvalue reference type will bind to any expression denoting a Foo
object. The move constructor takes one argument of type Foo&&
. This rvalue reference will only bind to modifiable rvalues. In fact, this overload will be preferred in the case of passing a modifiable rvalue.
This means that in Foo a(<some-expression>);
if the expression <some-expression>
is a modifiable rvalue, the move constructor will be chosen. Otherwise the copy constructor is chosen. Modifiable rvalues usually appear when denoting temporary objects (for example, an object returned from a function). It is also possible to force an expression to an rvalue expression by using std::move
, such as Foo a(std::move(b));
.
Upvotes: 4