可能不是BUG,但是我觉得很奇怪,有谁能告诉我为什么?#include "stdafx.h"
#include <iostream>
using namespace std;int _tmain(int argc, _TCHAR* argv[])
{
const int a(9);
const int * p;
p=const_cast<int *>(&a);
cout << "a=" << a << " before modify" << endl;
cout << "*p=" << *p << " before modify" << endl;
cout << "address of a=" << &a << " before modify" << endl;
cout << "p=" << p << " before modify" << endl << endl; *const_cast<int *>(&a)=111;
cout << "a=" << a << " before modify" << endl;
cout << "*p=" << *p << " before modify" << endl;
cout << "address of a=" << &a << " before modify" << endl;
cout << "p=" << p << " before modify" << endl; return 0;
}请注意,修改后,*p 和 a 打印出来的值竟然不一样,如果在*const_cast<int *>(&a)=111;出设置一个断点,你可以发现在此句前后,调试里a的值是不一样的。求教!谢谢
再问,如何给一个const的常量赋值?可以吗?
#include <iostream>
using namespace std;int _tmain(int argc, _TCHAR* argv[])
{
const int a(9);
const int * p;
p=const_cast<int *>(&a);
cout << "a=" << a << " before modify" << endl;
cout << "*p=" << *p << " before modify" << endl;
cout << "address of a=" << &a << " before modify" << endl;
cout << "p=" << p << " before modify" << endl << endl; *const_cast<int *>(&a)=111;
cout << "a=" << a << " before modify" << endl;
cout << "*p=" << *p << " before modify" << endl;
cout << "address of a=" << &a << " before modify" << endl;
cout << "p=" << p << " before modify" << endl; return 0;
}请注意,修改后,*p 和 a 打印出来的值竟然不一样,如果在*const_cast<int *>(&a)=111;出设置一个断点,你可以发现在此句前后,调试里a的值是不一样的。求教!谢谢
再问,如何给一个const的常量赋值?可以吗?
解决方案 »
- CFile类在回调函数中连续写入的问题
- 请问一下RGB或十六进制如何转成HSL
- CMenu的SetMenuItemBitmaps和DrawItem问题!知道的大哥帮忙解决一下以下难题,想知道的帮忙顶啊!
- 新手该不该看《vc6.0技术内幕》 《Windows核心编程》 ?
- 怎么用mfc activeX工程, 编写控件容器?
- rundll32.exe的问题,高手指点,100分送
- 如何直接在DLL中绘图?
- 请教网络编程
- 我向导生产一个CFormView,然后在void CFrmExView::OnInitialUpdate()
- 怎样在视图中用鼠标拖动来任意移动Bitmap和Icon呢?谢谢高手指引。希望附代码。
- 边城浪子爷爷请进来 一个查询xml里attribute的问题
- 菜鸟问题:在VC,或dotNET中建立一个ActiveX控件的过程是什么?
结果相反,呵呵
以前修改常字符串的时候也运到这个问题,感觉是优化的问题
00401482 mov ebx,esp
00401484 push 9
00401486 mov eax,esp
问题是如上的语句执行后,我在监视器里观察的值确实是变了,VC6和VC7都是如此。
但是实际cout出来的值却还是原来的那个。
晕了,到底能不能改呢?如何改?是不是微软的调试器有问题?
老大,没仔细看就别乱说,我用p指针去修改a的值了。管他用什么替换的,问题是我调试的时候在监视器确实看到a的值从9变成111了,但是cout出来的还是111
说话前摆脱仔细看下,谢谢
在Windows NT下无论如何不可能给 const 变量赋值的。因为这种变量位于只读内存区。就像写保护的软盘一样,软件不可能对它有所改变。而一个指向该只读内存的指针却不同。它所代表的变量有 COPY_ON_Write 属性。就是说,当你想写它的时候,如果内存是只读的,就把数据copy到另一个可写的内存里去,通过地址映射,面向用户的地址却不变。当然,这种机制只在WINdows下起作用。如果你那段代码运行在DOS下,就会输出你期望的结果,因为DOS没有内存保护机制。在windows下你非要变态得一定要把一个变量定义成const又要去改它的值的话,也不是没办法。你必须改变那个变量所在的内存的那一页的属性使得它可读写,该掉该值后,恢复其只读属性。
有没有办法看到它写到哪里去了?
用
VirtualProtectEx