When the move constructor is called

I would like to know when the move constructor is called in C ++ code.

This means that I know that when I call Foo a(b) , this is a copy constructor, so I need to encode a call to the move constructor.

+5
source share
2 answers

The move constructor is another constructor. If you have overloaded constructors, like any other functions that are overloaded, the choice of which constructor is called comes down to overload resolution rules. That is, when you build an object with Foo a(<some-expression>); There may be several possible constructors, and you need to choose.

The copy constructor takes one argument of type const Foo& . This lvalue reference type will be bound to any expression denoting a Foo object. The move constructor takes one argument of type Foo&& . This rvalue reference will only be bound to mutable r values. In fact, this overload will be preferable in the case of passing a variable value of r.

This means that in Foo a(<some-expression>); if the expression <some-expression> is a mutable value of r, a move constructor will be selected. Otherwise, the copy constructor is selected. Modified values โ€‹โ€‹of r usually appear when designating temporary objects (for example, the object returned by a function). You can also force an expression into an rvalue expression using std::move , for example Foo a(std::move(b)); .

+4
source

In general, we should say this by specifying the rvalue reference argument. For instance:

 template<class T> void swap(T& a, T& b) { T tmp = std::move(a); a = std::move(b); b = std::move(tmp); } 

move() is a standard library function that returns an rvalue reference to its argument move(x) means "give an rvalue reference to x". That is, std::move(x) does not move anything, instead, it allows the user to move x.

Source: C ++ programming language (B. Stroustrup)

+3
source

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


All Articles