c++ - 为什么 C++ 中的引用不是 "const"?

标签 c++ reference constants language-lawyer decltype

我们知道一个“const 变量”表示一旦赋值就不能改变变量,像这样:

int const i = 1;
i = 2;

上面的程序将无法编译; gcc 提示错误:

assignment of read-only variable 'i'

没问题,我可以理解,但是下面的例子超出了我的理解范围:

#include<iostream>
using namespace std;
int main()
{
    boolalpha(cout);
    int const i = 1;
    cout << is_const<decltype(i)>::value << endl;
    int const &ri = i;
    cout << is_const<decltype(ri)>::value << endl;
    return 0;
}

输出

true
false

很奇怪。我们知道,一旦引用被绑定(bind)到一个名称/变量,我们就不能改变这个绑定(bind),我们改变它的绑定(bind)对象。所以我想ri的类型应该和i一样:当iint const时,为什么ri 不是 const 吗?

最佳答案

这似乎违反直觉,但我认为理解这一点的方法是认识到,在某些方面,引用被视为句法指针

这对于 指针 来说似乎是合乎逻辑的:

int main()
{
    boolalpha(cout);

    int const i = 1;
    cout << is_const<decltype(i)>::value << endl;

    int const* ri = &i;
    cout << is_const<decltype(ri)>::value << endl;
}

输出:

true
false

这是合乎逻辑的,因为我们知道不是 指针对象 是 const(它可以指向别处),而是被指向的对象。

所以我们正确地看到 pointer 本身的 constness 返回为 false

如果我们想让 pointer 本身成为 const 我们必须说:

int main()
{
    boolalpha(cout);

    int const i = 1;
    cout << is_const<decltype(i)>::value << endl;

    int const* const ri = &i;
    cout << is_const<decltype(ri)>::value << endl;
}

输出:

true
true

所以我认为我们看到了与 reference 的句法类比。

然而 references 在语义上与指针不同,尤其是在 一个 关键方面,一旦绑定(bind),我们就不能重新绑定(bind)对另一个对象的引用.

因此,即使 referencespointers 共享相同的语法,但规则是不同的,因此语言阻止我们声明 reference 本身 const 像这样:

int main()
{
    boolalpha(cout);

    int const i = 1;
    cout << is_const<decltype(i)>::value << endl;

    int const& const ri = i; // COMPILE TIME ERROR!
    cout << is_const<decltype(ri)>::value << endl;
}

我认为我们不允许这样做,因为当语言规则阻止 reference 以与 pointer 可以(如果没有声明const)。

所以回答这个问题:

Q) Why “reference” is not a “const” in C++?

在您的示例中,语法使被引用的事物 const 与声明 pointer 的方式相同。

无论对错,我们都不允许将 reference 本身设为 const,但如果我们这样做,它看起来像这样:

int const& const ri = i; // not allowed

Q) we know once a reference is bind to a name/variable, we cannot change this binding, we change its binded object. So I suppose the type of ri should be same as i: when i is a int const, why ri is not const?

为什么 decltype() 没有传递到 referece 绑定(bind)的对象上?

我想这是为了与 pointers 语义等价,也许 decltype()(声明类型)的功能是回顾 声明的内容 在绑定(bind)发生之前。

关于c++ - 为什么 C++ 中的引用不是 "const"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38044834/

相关文章:

java - 在 Java 中,我可以放置所有常量的文件类型是什么?

C++ 并行化 : Fast way to "reinitialize" array

c++ - 重新缩放或缩放光标后的 qwt plot 移动曲线

SQL 查询引用

java - 涉及魔数(Magic Number)的全局常量的最佳实践

c - 指针创建常量字符串文字,为什么?

c++ - std::string 连接的运行时依赖

c++ - 在使用pthread_create 创建的线程之间读写管道时是否需要关闭fds?

c++ - C++ 引用在内存方面的外观如何?

php - 如何检查变量是否在PHP中通过引用传递