向运算符添加 ref 限定符将消除进行右值赋值的可能性
例如,用g++ -std=c++14 bar.cpp && ./a.out
#include <cstdio>
struct foo
{
void operator+=(int x) & { printf("%d\n", x+2); }
};
int main()
{
foo() += 10;
}
会给你
$ g++ -std=c++14 bar.cpp && ./a.out
bar.cpp: In function ‘int main()’:
bar.cpp:14:14: error: passing ‘foo’ as ‘this’ argument discards qualifiers [-fpermissive]
14 | foo() += 10;
| ^~
bar.cpp:6:10: note: in call to ‘void foo::operator+=(int) &’
6 | void operator+=(int x) & { printf("%d\n", x+2); }
| ^~~~~~~~
您当然可以通过添加显式来“解决”这个问题&&
#include <cstdio>
struct foo
{
void operator+=(int x) & { printf("%d\n", x+2); }
void operator+=(int x) && { printf("%d\n", x+3); }
};
int main()
{
foo() += 10;
}
输出
$ g++ -std=c++14 bar.cpp && ./a.out
13
但是添加 aconst &
也会让你调用+=
结构实例。
#include <cstdio>
struct foo
{
void operator+=(int x) & { printf("%d\n", x+2); }
void operator+=(int x) const & { printf("%d\n", x+4); }
};
int main()
{
foo() += 10;
}
输出
$ g++ -std=c++14 bar.cpp && ./a.out
14
要“解决”这个问题,const &&
必须明确删除
#include <cstdio>
struct foo
{
void operator+=(int x) & { printf("%d\n", x+2); }
void operator+=(int x) const & { printf("%d\n", x+4); }
void operator+=(int x) const && = delete;
};
int main()
{
foo() += 10;
}
输出
$ g++ -std=c++14 bar.cpp && ./a.out
bar.cpp: In function ‘int main()’:
bar.cpp:14:14: error: use of deleted function ‘void foo::operator+=(int) const &&’
14 | foo() += 10;
| ^~
bar.cpp:9:10: note: declared here
9 | void operator+=(int x) const && = delete;
| ^~~~~~~~
为什么是这样?为什么添加 ref-qualifier 会隐式删除右值分配?但是将 cv 限定符与 ref 限定符一起添加似乎隐式添加了右值赋值?
我确定我在这里遗漏了一些明显的东西。但是 Google-Wan Kenobi 似乎无法帮助我理解。