Move constructor signature

旧城冷巷雨未停 提交于 2019-11-29 10:30:31
Jonathan Wakely

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!