#include <iostream>
using namespace std;
void f(const char * const &s) {
cout << "lvalue" << endl;
}
void f(const char * const &&s) {
cout << "rvalue" << endl;
}
int main()
{
char s[] = "abc";
f("abc");
f(s);
}
输出:
rvalue
rvalue
为什么输出不是“右值左值”?
最佳答案
字符串文字和 s
都不是指针(它们是数组),因此标准的相关部分是 [conv.array]:
An lvalue or rvalue of type "array of
N
T
" or "array of unknown bound ofT
" can be converted to a prvalue of type "pointer toT
". The result is a pointer to the first element of the array.
注意
char const *p = s;
f(p);
打印“左值”,以表明这与您对指针的预期一样有效。
附录回复:评论:在
的情况下char *p = s;
f(p);
如果右值重载存在则打印“右值”,但如果删除右值重载则不会导致编译器错误,标准的另外两个部分开始发挥作用——其中一个部分似乎禁止 char* 的绑定(bind)
to char const *const &
一共,另开一个窗口回来。
第一个是[dcl.init.ref]/4,其中声明
Given types "cv1
T1
" and "cv2T2
", "cv1T1
" is reference-related to "cv2T2
" ifT1
is the same type asT2
, orT1
is a base-class ofT2
. "cv1T1
" is reference-compatible with "cv2T2
" ifT1
is reference-related toT2
and cv1 is the same cv-qualification as, or greater cv-qualification than, cv2. (...)
它详细介绍了引用初始化的精确规则,所有这些都是相关的,但不幸的是对于 SO 答案来说太长了。长话短说,对 cv1 T1
的引用可以用 cv2 T2
的对象初始化,如果两者是引用兼容的。
这个法律术语对我们的情况意味着 char*
和 char const *
不是reference-compatible(尽管 char *
和 char *const
会是),因为 char*
不是 char const *
也不是其他。如果您认为以下非法代码段在其他情况下是合法的,则此限制是有意义的:
const char c = 'c';
char *pc;
const char*& pcc = pc; // #1: not allowed
pcc = &c;
*pc = 'C'; // #2: modifies a const object
这改编自 [conv.qual]/4 中的一个类似示例,该示例使用指向指针的指针来演示相同的问题。
[conv.qual] 也是打开窗口的其他相关部分。它在 [conv.qual]/1 中说:
A prvalue of type "pointer to cv1
T
" can be converted to a prvalue of type "pointer to cv2T
" if "cv2T
" is more cv-qualified than "cv1T
"
由此可见,char*
可以转换为 char const *
1(与 引用兼容char const *const
),这就是为什么如果删除了 f
的右值重载,代码仍然可以编译。但是,此转换的结果是纯右值,因此如果它存在,则在重载决策中优先选择右值重载。
1 char*
glvalue -> char*
prvalue (by [conv.lval]) -> char const *
纯右值)
关于c++ - 使用对 const char * 的右值引用的重载解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28680325/