Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 高水平还是低水平的康斯特内斯?_C++_C++11_Constants - Fatal编程技术网

C++ 高水平还是低水平的康斯特内斯?

C++ 高水平还是低水平的康斯特内斯?,c++,c++11,constants,C++,C++11,Constants,我正在处理,如果我理解正确: 顶级常量应用于对象本身 低级常量意味着被引用对象的值是常量,这使得被引用对象成为顶级常量 现在是问题对于既不是顶级也不是低级的常量,是否有命名约定?即指针本身不是常量,但它以恒定方式指向非常量对象?或者这是低水平康斯特的一个特例?例如: int i {0]; int j {42}; // The following pointer is not const itself. // The object it's pointing to is not 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
接受轨道上的亮度竞赛后编辑答案:
我的IDE将它们称为只读指针,这对我来说很有意义 尽管可以使用此难看的强制转换更改引用的对象:

*const_cast<int*>(pci) = 21;
*常量(pci)=21;
不,不是真的

您所做的区分是在类型为
const
-qualified的对象和类型为
const
-qualified的表达式之间进行的

因为(从使用的角度来看)哪一个在起作用几乎不重要†,所以在任何给定的情况下都没有有意义的术语来区分它们

不可否认,这使得解释为什么下面的程序完全有效且定义良好(如果风格真的很糟糕),尽管去掉了
常量
,还是有点麻烦:

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);
}
void foo(const int&x)
{
//表达式'x'的类型为'const int&`(在衰减之前),
//但是在去掉常量之后,我们可以修改
//referent,因为它恰好是非-const`。
const_cast(x)=66;
}
int main()
{
int x=42;//对象不是常量!
foo(x);
}
尽管如此,我还是不太确定你的“低级常量”。这些术语甚至不是完全对称的!Pfft


†在上面的
foo()
中,我们实际上不会编写
const\u cast
,因为我们假设所有输入都是对对象的引用,这些对象实际上是
const

迁移给程序员的。请注意,直到最近,才很难找到一个正确的答案。谢谢你的回答。本书中通篇使用了顶级/低级const术语,所以我认为它们是常用的。@robsn:原来“顶级”是标准术语。
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);
}