balki
balki

Reputation: 27694

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?

Upvotes: 8

Views: 2334

Answers (2)

Jonathan Wakely
Jonathan Wakely

Reputation: 171491

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.

Upvotes: 9

user1899861
user1899861

Reputation:

Some background on this feature's intent.

Rvalue references - From Bjarne Stroustrup's Blog

A Proposal to Add Move Semantics Support to the C++ Language

An interesting question. I read, somewhere, an explanation of this question by Stroustrup, but can't seem to find it back. Hope the above helps in its stead.

Upvotes: 0

Related Questions