此赋值运算符后的&符是什么意思? [英] What does an ampersand after this assignment operator mean?

查看:152
本文介绍了此赋值运算符后的&符是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关规则五的不错答案,我注意到了我不记得以前看过了:

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;
  ...
};

& 字符放置在 = 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?

推荐答案

这是一个允许C ++ 11非静态成员函数区分的功能的一部分

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.

在上面的例子中,这里默认的拷贝赋值运算符只能在lvalue上被调用。这使用已经建立的左值和右值引用绑定的规则;这只是为 建立它们。

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{};

这不是:

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;

这篇关于此赋值运算符后的&符是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆