Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the move constructor called in the `std::move()` function?

The function std::move() is defined as

template<typename T>
typename std::remove_reference<T>::type&& move(T && t)
{ 
    return static_cast<typename std::remove_reference<T>::type&&>( t ); 
}

There are four places where I can imagine the move constructor to be called:

  1. When the parameter is passed.
  2. When the cast is performed.
  3. When the result is returned.
  4. Not in the std::move() function itself but possibly at the place where the returned reference ultimately arrives.

I would bet for number 4, but I'm not 100% sure, so please explain your answer.

like image 397
Ralph Tandetzky Avatar asked Feb 07 '13 11:02

Ralph Tandetzky


People also ask

When is a move constructor called?

A move constructor is called: when an object initializer is std::move(something) when an object initializer is std::forward<T>(something) and T is not an lvalue reference type (useful in template programming for "perfect forwarding") when an object initializer is a temporary and the compiler doesn't eliminate the copy/move entirely.

Which is faster move constructor or copy constructor in C++?

As shown above “move constructor” is faster than “copy constructor” as move constructor is using “char *” of object “mv1” to object “mv3”. Because of this performance of move constructor is better than copy constructor.

What is the use of MOVE function in C++?

std::move () is a function used to convert an lvalue reference into the rvalue reference. Used to move the resources from a source object i.e. for efficient transfer of resources from one object to another. std::move () is defined in the <utility> header.

What happens when you call move () on a const object?

Calling a std::move () on a const object usually has no effect. It doesn’t make any sense to steal or move the resources of a const object. Copy semantics is used as a fallback for move semantics if and only if copy semantics is supported.


1 Answers

There is no move construction going on. std::move() accepts a reference and returns a reference. std::move() is basically just a cast.

Your guess 4. is the right one (assuming that you are actually calling a move constructor in the end).

like image 193
Ali Avatar answered Nov 03 '22 07:11

Ali