c++ - 顶级或低级常量或两者都不是?

标签 c++ c++11 constants

我正在处理 C++ Primer如果我理解正确的话:

  • 顶级常量适用于对象本身。
  • 低级常量意味着被引用对象是常量,这使得被引用对象成为顶级常量。
// A plain int.
int i {0};

// Top-level const ints.
const int ci {42};
const int ci2 {0};

// A low-level pointer to const int.
const int * pci {&ci};

// Low-level, because the referenced object can't be changed.
*pci = 0; // error

// But not top-level, because it can be changed to point to another object.
pci = &ci2; // fine

// This is both top-level and low-level const
// because both the pointer and the object it
// points to are const:
const int * const cpci {&ci};
*cpci = 0;   // error
cpci = &ci2; // error

现在是问题。 对于既不是顶级也不是低级的常量是否有命名约定?即指针本身不是 const 但它以常量方式指向非常量对象?或者这是低级常量的特例?示例:

int i {0];
int j {42};

// The following pointer is not const itself.
// The object it's pointing to is not const but
// it can't be manipulated through the pointer.
const int * pci {&i};
*pci = 42; // error

// All these are fine:
++i;
pci = &j;
++j;

*pci = 42; // error as above

在接受 Lightness Races in Orbit 的回答后编辑:
我的 IDE 将它们称为只读指针,这对我来说很有意义 虽然引用的对象可以用这个丑陋的转换来改变:

*const_cast<int*>(pci) = 21;

最佳答案

不,不是真的。

您要区分的是 objectconst -限定类型,以及一个带有 const表达式 -限定类型。

因为(从使用的角度来看)玩哪个游戏并不重要,因此在任何给定情况下都没有有意义的术语来区分它们。

诚然,尽管放弃了 const,但解释为什么以下程序完全有效且定义明确(如果真的是非常糟糕的风格)确实有点麻烦。 :

void foo(const int& x)
{
   // the expression `x` has type `const int&` (before decay),
   // but after casting away the constness we can modify the
   // referent, because it happens to actually be non-`const`.
   const_cast<int&>(x) = 66;
}

int main()
{
   int x = 42;    // object is not const!
   foo(x);
}

尽管"top-level const" is standard terminology 物有所值,我不太确定你的“低级常量”。这些术语甚至不完全对称!噗。

foo()上面我们实际上不会写const_cast因为我们假设所有输入都是对对象的引用,这些对象实际上是 const .

关于c++ - 顶级或低级常量或两者都不是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34519369/

相关文章:

c++ - 通过构造函数初始化枚举

c++ - 注释变量与 Doxygen 内联会带来任何惩罚吗?

c++ - 用模板初始化的 N 维 std::array

c++ - Const 正确性和运算符 *

C# - 在运行时初始化常量字段

c++ - 转换 Derived** → Base** 是错误的吗?还有什么选择?

c++ - 在 Linux(Ubuntu 13.10 和 14.04)下运行没​​有 QtCoreApplication/QCoreApplication 的 Qt C++ 代码

c++ - 混合使用 boost 锁和标准锁是否安全?

c++ - C++ 中的迭代器和模板

c - 在c中,char类型的参数与const char参数类型不兼容