增加顶级常量指针时发生了什么
What happend when increasing a top-level const pointer?
当我试图找出顶级常量和const_cast时,我编写了一些代码,如下所示。
int main()
{
// m is a top-level const
const int m = 10;
// this is an undefined behavior according to *Primer c++*
// but I still compile and run this without warning.
int *q = const_cast<int *>(&m);
(*q)++;
//Then I print the address and the value
cout<< "the value of address "<< q <<" is "<< *q <<endl;
cout<< "the value of address "<< &m <<" is "<< m <<endl;
return 0;
}
打印结果让我感到困惑。
the value of address 0x7ffee6a43ad8 is 11
the value of address 0x7ffee6a43ad8 is 10
这是未定义的行为之一吗?当我做"(*q(++"时到底发生了什么?
提前致谢
请注意,您的代码不执行*q++
,它(*q)++
。
使用*q++
,您可以递增指针。有了(*q)++
,你就会增加它所指向的内容。
这一切都很好,除了q
指向一个常量值。尝试修改常量值实际上是未定义的行为。
如果您改为*q++
并递增指针,则不会修改常量值,因此可以。另一方面,它不再指向有效对象,当您取消引用q
打印它指向的值时,您将拥有 UB。
这是未定义的行为之一吗?
是的。您实际上有两行,每行都可能导致未定义的行为。
int *q = const_cast<int *>(&m);
和
(*q)++;
在第一个中,您将使用 const_cast
来删除使用 const
限定符创建对象时指针指向的对象的const
-ness。
在第二个中,您正在修改const
对象的值。
当我做"(*q++("时到底发生了什么?
您必须查看汇编代码才能弄清楚编译器如何处理它。它可以做任何它想做的事。我们不能责怪它做了它所做的事情。
相关文章:
- 此测试()中发生了什么意外过程?为什么总是覆盖 ch[0 1 2..]?
- 这C++代码中发生了什么C++(指数函数)
- 哪种方式更快?究竟发生了什么,我们没有看到什么?
- 从"LLONG_MAX 秒"构造 std::chrono::毫秒变量时发生了什么?
- 这个片段中关于 n 在 pc[i] 中的表示发生了什么
- istringstream,num1 和 num2 在这里发生了什么?
- 究竟发生了什么,我们需要在 c++ 中双重调度/访客
- 我是否能够确定在部署一个程序后发生了什么,我在数组末尾写入?
- 这个阶乘程序内部发生了什么?
- C++ - *(int**) 地址?这里发生了什么?
- C++用用户输入在循环中填充 char 数组:输入整个字符串时到底发生了什么?
- 让对象知道它创建的 show 函数中发生了什么
- 这里的矢量数组发生了什么?
- 增加顶级常量指针时发生了什么
- 当另一端将其关闭时,插座发生了什么
- C :我堆栈顶部发生了什么
- 此递归中发生了什么?我需要仅使用递归/无循环来计算和备份
- 这个 std::vector 构造函数中发生了什么
- 编译器认为 int 是一个字符串.发生了什么事情
- 无法运行简单的 std::async 和 std::future 测试程序。错误:"has initializer but incomplete type."发生了什么?