这是对this question的后续行动
请考虑以下代码段
void f(int const &); // f "guarantees" not to change its parameter
int main()
{
int const a = 42; // a is not modifiable
f(a); // so f definitely can't modify a
// (at least not without invoking UB), that's great
int b = 42; // b is modifiable
f(b); // but f could modify b legally? huh? not so great
}
我的理解:f可以only修改b,并且它must使用const_cast进行修改。同样,这通常是一个坏主意,不应该这样做。此外,还有某种原因导致该语言中存在一种忽略const的机制。
如果我的理解是正确的,那么我的问题是,有没有一种方法可以编写保证的函数而不修改其参数。即是否可以执行以下操作
void f(int const_really &); // f guarantees not to change its parameter
int main()
{
int b = 42; // even if b is modifiable
f(b); // f is not allowed to modify b legally
// (or is UB if it does)
}
现在有可能吗?
如果不是,那可以添加到该语言中吗?
如果没有,是否有某些原因使它永远无法完成?
该关键字为const
。它已经提供了C ++所能提供的强有力的保证-如果该函数的实现者选择的话,那就没有。
如果您决定放弃const,则所有赌注都消失了,您最好知道自己在做什么。
C ++是一种始终允许您以一种或另一种方式丢弃任何内容的语言。因此,无论您引入什么新的const_really
关键字,它都将在const
现在的位置处向左-如果程序员决定忽略它并进行大量转换,则将无能为力。如果程序员需要,禁止这样做将违反C ++的核心宗旨-绝对控制。不需要新的关键字,因为添加一个关键字不会带来任何好处。