What does an ampersand after this assignment operator mean?

*爱你&永不变心* 提交于 2019-11-26 19:06:44

问题


I was reading through this nice answer regarding the "Rule-of-five" and I've noticed something that I don't recall seeing before:

class C {
  ...
  C& operator=(const C&) & = default;
  C& operator=(C&&) & = default;
  ...
};

What is the purpose of the & character placed in front of = default for the copy assignment operator and for the move assignment operator? Does anyone have a reference for this?


回答1:


It's part of a feature allowing C++11 non-static member functions to differentiate between whether they are being called on an lvalues or rvalues.

In the above case, the copy assignment operator being defaulted here can only be called on lvalues. This uses the rules for lvalue and rvalue reference bindings that are well established; this just establishes them for this.

In the above case, the copy assignment operator is defaulted only if the object being copied into can bind to a non-const lvalue reference. So this is fine:

C c{};
c = C{};

This is not:

C{} = c;

The temporary here cannot bind to an lvalue reference, and thus the copy assignment operator cannot be called. And since this declaration will prevent the creation of the usual copy assignment operator, this syntax effectively prevents copy-assignment (or move-assignment) to temporaries. In order to restore that, you would need to add a && version:

C& operator=(const C&) && = default;
C& operator=(C&&) && = default;



回答2:


It means that that function is only callable on lvalues. So this will fail because the assignment operator function is called on an rvalue object expression:

C() = x;


来源:https://stackoverflow.com/questions/12306226/what-does-an-ampersand-after-this-assignment-operator-mean

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