关于 const_cast的有意思的问题
2009-05-08 17:51
316 查看
#include <iostream>
using namespace std;
int main()
{
//TODO: Add your code here
const int a = 1;
int *p = 0;
cout << "a = " << a << endl;
//!: p = &a can not cast a const int* to int*
p = const_cast<int*>(&a);
*p = 5;
cout << "a = " << a << endl;
cout << "*p = " << *p << endl;
int b;cin >> b ;
return 0;
}
请问程序的结果为什么是
a = 1
a = 1
*p = 5
而不是
a = 1
a = 5
*p = 5
答案:
对于常量,是编译时直接求值的(无需求值的直接替换).
cout << "a = " << a << endl;
相当于
cout << "a = " << 1 << endl;
其实a所在的内存的值已经改为5了.
通过汇编代码可以看清楚:
16: cout << "a = " << a << endl;
004015E4 push offset @ILT+195(std::endl) (004010c8) // 参数''a=''入栈
004015E9 push 1 // 参数a入栈
17: cout << "*p = " << *p << endl;
0040160B push offset @ILT+195(std::endl) (004010c8)
00401610 mov edx,dword ptr [ebp-8]
00401613 mov eax,dword ptr [edx] // 参数*p入栈
对P的操作和一般的指针变量完全一样,先找地址,然后取值。
对a的操作根本就直接用1,所以cout<<a看起来就象cout<<"1";
using namespace std;
int main()
{
//TODO: Add your code here
const int a = 1;
int *p = 0;
cout << "a = " << a << endl;
//!: p = &a can not cast a const int* to int*
p = const_cast<int*>(&a);
*p = 5;
cout << "a = " << a << endl;
cout << "*p = " << *p << endl;
int b;cin >> b ;
return 0;
}
请问程序的结果为什么是
a = 1
a = 1
*p = 5
而不是
a = 1
a = 5
*p = 5
答案:
对于常量,是编译时直接求值的(无需求值的直接替换).
cout << "a = " << a << endl;
相当于
cout << "a = " << 1 << endl;
其实a所在的内存的值已经改为5了.
通过汇编代码可以看清楚:
16: cout << "a = " << a << endl;
004015E4 push offset @ILT+195(std::endl) (004010c8) // 参数''a=''入栈
004015E9 push 1 // 参数a入栈
17: cout << "*p = " << *p << endl;
0040160B push offset @ILT+195(std::endl) (004010c8)
00401610 mov edx,dword ptr [ebp-8]
00401613 mov eax,dword ptr [edx] // 参数*p入栈
对P的操作和一般的指针变量完全一样,先找地址,然后取值。
对a的操作根本就直接用1,所以cout<<a看起来就象cout<<"1";
相关文章推荐
- 关于const_cast(str.c_str())的使用问题
- C++关于参数为const引用类型的函数调用参数成员函数的一个问题
- [c/c++]关于const_cast
- 优化问题关于const第二篇
- 关于const char*和char*、const char** 和char** 赋值问题
- C++的const_cast的问题
- 从const_cast引出的一个问题
- const_cast的问题
- 关于const_cast
- 关于const记录类型全局变量赋初值的问题
- 关于const与函数重载问题
- 关于 #define 和 const 定义常量所回想起的问题
- const_cast 的问题
- 关于CString剖析,“strcmp”: 不能将参数1从“CString”转换为“const char *”问题
- 关于cstring ->string-> const char * 用U2A一步转换 错误的内存问题
- 程序中变量的内存安排和const_cast问题
- 关于c++ 强制转换类型运算符 static_cast、dynamic_cast、reinterpret_和const_cast
- 关于const和define的内存分配问题的总结
- 关于 Unity UI 中 GraphicRaycaster.Raycast 数量巨大的问题
- 关于 define 和const 的问题