由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 弱问个C++ 问题 (const_cast)
相关主题
C++ Q83: 这个const_cast什么意思?问个C++ delete[]问题
问一道无聊的bloomberg电面题请教一段volatile和多线程的代码
问个超级小问题新鲜出炉的Broadcom电话面试题
这个C++程序的运行结果是什么一个C语言概念题
一个C++的问题!问道面试体(software)
两道面试题,请大家说说看法做硬件模拟器的职位有前途吗
C++ volatile请教c++ is too nasty
问个基础题,大家不要笑我小白问题:如何能短时间内提高C++能力?
相关话题的讨论汇总
话题: endl话题: cout话题: const话题: int话题: 0xbf93a65c
进入JobHunting版参与讨论
1 (共1页)
w****g
发帖数: 206
1
运行一下 程序:
int main() {
const int i = 0;
int * j;
cout << "&j=" << &j << endl;
cout << "&i=" << &i << endl;
cout << "j=" << j << endl;
j = const_cast(&i);
*j = 2;
cout << "i=" << i << endl;
cout << "*j=" << *j << endl;
cout << "j=" << j << endl;
cout << "&i=" <<&i < }
得到结果:
&j=0xbf93a658
&i=0xbf93a65c
j=0
i=0
*j=2
j=0xbf93a65c
&i=0xbf93a65c
这就是说:j 和&i是一样的,但是为什么i和*j不一样呢?
s*****n
发帖数: 5488
2
looks like j is int pointer. and const-cast just removes the const of the
pointer.

【在 w****g 的大作中提到】
: 运行一下 程序:
: int main() {
: const int i = 0;
: int * j;
: cout << "&j=" << &j << endl;
: cout << "&i=" << &i << endl;
: cout << "j=" << j << endl;
: j = const_cast(&i);
: *j = 2;
: cout << "i=" << i << endl;

M********5
发帖数: 715
3
This is undefined behavior of const_cast. So that's the reason why you need
to take care when you use those cast features.
You can google const_cast undefined behavior.
r**u
发帖数: 1567
4
This doesn't explain his question. Since i & *j points to the same address,
why i = 0 but *j = 2?

【在 s*****n 的大作中提到】
: looks like j is int pointer. and const-cast just removes the const of the
: pointer.

x***y
发帖数: 633
5
change the definition of "const int i = 0" to
"volatile const int = 0", then i will be 2. The reason is due to
optimization, that i will be read from register, not from memory.

【在 w****g 的大作中提到】
: 运行一下 程序:
: int main() {
: const int i = 0;
: int * j;
: cout << "&j=" << &j << endl;
: cout << "&i=" << &i << endl;
: cout << "j=" << j << endl;
: j = const_cast(&i);
: *j = 2;
: cout << "i=" << i << endl;

h**k
发帖数: 3368
6
volatile关键字会强迫从内存中读取,而不会只返回寄存器中的值。
我觉得是compiler直接优化,把输出i的值的语句中的i直接替换成0,因为i声明成
const变量。

【在 x***y 的大作中提到】
: change the definition of "const int i = 0" to
: "volatile const int = 0", then i will be 2. The reason is due to
: optimization, that i will be read from register, not from memory.

d*********i
发帖数: 628
7
学习了!
f****4
发帖数: 1359
8
学习了~~
1 (共1页)
进入JobHunting版参与讨论
相关主题
小白问题:如何能短时间内提高C++能力?一个C++的问题!
最快的语言还是C/C++吗?两道面试题,请大家说说看法
我觉得任何时候大家讨论的语言就两种,C++和最热的语言。C++ volatile请教
C++ 题目问个基础题,大家不要笑我
C++ Q83: 这个const_cast什么意思?问个C++ delete[]问题
问一道无聊的bloomberg电面题请教一段volatile和多线程的代码
问个超级小问题新鲜出炉的Broadcom电话面试题
这个C++程序的运行结果是什么一个C语言概念题
相关话题的讨论汇总
话题: endl话题: cout话题: const话题: int话题: 0xbf93a65c