c++ - 使用对 const char * 的右值引用的重载解析

标签 c++ c++11 lvalue rvalue

#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 of T" can be converted to a prvalue of type "pointer to T". 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 "cv2 T2", "cv1 T1" is reference-related to "cv2 T2" if T1 is the same type as T2, or T1 is a base-class of T2. "cv1 T1" is reference-compatible with "cv2 T2" if T1 is reference-related to T2 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 cv2 T" if "cv2 T" is more cv-qualified than "cv1 T"

由此可见,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/

相关文章:

c++ - 了解 C++ 模板元编程

c++ - 为什么清理istringstream会失败?

c++ - Pimpl Idiom 的嵌套名称说明符中使用的不完整类型

c++ - 为什么此代码生成错误 C2105 而不是 C3892?

c - 下面提到的代码中左值错误的原因是什么?

C++ --- 这些数学函数/常量不应该是未定义的吗?

c++ - 在函数中定义结构体数组

c - 为什么 foo((&i)++) 给出 Lvalue required 错误。没有关联的数组

c++ - 数组( vector )中大于某个值的元素的起始索引和结束索引

c++ - 为什么要删除new分配的内存呢?