【问题标题】:Top-level or low-level constness or neither?顶级或低级常量或两者都不是?
【发布时间】:2015-12-29 21:28:47
【问题描述】:

我正在处理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 但它以恒定的方式指向非 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

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

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

【问题讨论】:

标签: c++ c++11 constants


【解决方案1】:

不,不是。

您所做的区别在于具有const 限定类型的对象 和具有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 的对象的引用。

【讨论】:

  • 感谢您的回答。顶层/底层 const 术语在整本书中都有使用,所以我认为它们是常用的。
  • @robsn:原来“顶级”是标准术语。
猜你喜欢
  • 1970-01-01
  • 2018-09-14
  • 2011-03-14
  • 1970-01-01
  • 2015-08-14
  • 2020-04-17
  • 2014-08-28
  • 2022-07-16
  • 2016-02-29
相关资源
最近更新 更多