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

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

问题描述

我正在阅读这个关于五分法则"的不错的答案,我注意到一些事情我不记得以前看过:

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.

在上述情况下,此处默认的复制赋值运算符只能在左值上调用.这使用了完善的左值和右值引用绑定规则;这只是为 this 建立它们.

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天全站免登陆