Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move constructor signature

From this reference, it allows a const rvalue as a move constructor

Type::Type( const Type&& other );

How can a movable object be const? Even if this was technically allowed, is there a case where such declaration would be useful?

like image 469
balki Avatar asked Dec 28 '12 09:12

balki


1 Answers

How can a movable object be const?

It can't, but that's not what the language says. The language says that a constructor with that signature is a "move constructor" but that doesn't mean the argument gets moved from, it just means the constructor meets the requirements of a "move constructor". A move constructor is not required to move anything, and if the argument is const it can't.

is there a case where such declaration would be useful?

Yes, but not very often. It can be useful if you want to prevent another constructor being selected by overload resolution when a const temporary is passed as the argument.

struct Type
{
  template<typename T>
    Type(T&&);  // accepts anything

  Type(const Type&) = default;    
  Type(Type&&) = default;
};

typedef const Type CType;

CType func();

Type t( func() );   // calls Type(T&&)

In this code the temporary returned from func() will not match the copy or move constructors' parameters exactly, so will call the template constructor that accepts any type. To prevent this you could provide a different overload taking a const rvalue, and either delegate to the copy constructor:

Type(const Type&& t) : Type(t) { }

Or if you want to prevent the code compiling, define it as deleted:

Type(const Type&& t) = delete;

See https://stackoverflow.com/a/4940642/981959 for examples from the standard that use a const rvalue reference.

like image 102
Jonathan Wakely Avatar answered Oct 18 '22 07:10

Jonathan Wakely