【发布时间】:2009-08-20 21:20:47
【问题描述】:
我有
class Fred
{
public:
void inspect() const {};
void modify(){};
};
int main()
{
const Fred x = Fred();
Fred* p1;
const Fred** q1 = reinterpret_cast<const Fred**>(&p1);
*q1 = &x;
p1->inspect();
p1->modify();
}
怎么可能做到 常量弗雷德** q1 = &p1 通过指针转换?
(我刚刚读到这可能是可能的)
感谢您的回答。 const_cast 确实适用于对象
#include <iostream>
#include <stdio.h>
using namespace std;
class Fred
{
int a;
public:
Fred(){};
Fred(int a_input)
{
a = a_input;
};
void inspect() const
{
cout << "Inspect called"<< endl;
cout << "Value is ";
cout << a << endl;
};
void modify()
{
cout << "Modify called" << endl;
a++;
};
};
int main()
{
const Fred x = Fred(7);
const Fred* q1 = &x;
Fred* p1 = const_cast<Fred*>(q1);
p1->inspect();
p1->modify();
p1->inspect();
x.inspect();
*p1 = Fred(10);
p1->inspect();
}
给予
Inspect called
Value is 7
Modify called
Inspect called
Value is 8
Inspect called
Value is 8
Inspect called
Value is 10
Inspect called
Value is 10
但是,对于预定义的类型,它不起作用:
int main()
{
const double a1 = 1.2;
const double* b1 = &a1;
cout << "a1 is " << (*b1) << endl;
cout << "b1 is " << b1 << endl;
double* c1 = const_cast<double*>(&a1);
cout << "b1 is " << b1 << endl;
cout << "c1 is " << c1 << endl;
double* d1 = static_cast<double*>(static_cast<void*>(c1));
cout << "d1 is " << d1 << endl;
cout<< "*d1 is " << *d1 << endl;
*d1=7.3;
cout<< "*d1 is " << *d1 << endl;
cout<< "*d1 address is "<< d1 << endl;
cout << "a1 is " << a1 << endl;
cout << "a1 address is" << &a1 << endl;
cout<< "*d1 is " << *d1 << endl;
cout<< "*d1 address is "<< d1 << endl;
double f1=a1;
printf("f1 is %f \n", f1);
}
导致:
a1 is 1.2
b1 is 0xffbff208
b1 is 0xffbff208
c1 is 0xffbff208
d1 is 0xffbff208
*d1 is 1.2
*d1 is 7.3
*d1 address is 0xffbff208
a1 is 1.2
a1 address is0xffbff208
*d1 is 7.3
*d1 address is 0xffbff208
f1 is 1.200000
显然,g++ 编译器进行了优化,以便在找到 a1 时将其替换为 1.2,因此,即使它在堆栈上的值已更改,它也不在乎。
(在我的情况下,我在直接读取 *b1、*c1 时遇到了问题,因此我必须进行双重静态转换——重新解释转换不起作用)。
有没有办法真正改变a1,“正常”编译,因此没有优化就不能编译(所以我超越了优化效果)?
【问题讨论】:
-
感谢重新格式化!更容易阅读!
-
您添加的新信息实际上是一个不同的问题。将来考虑将其发布(它也会以这种方式获得更多答案)。至于 const 原语的编译器优化:如果您不希望编译器对其进行优化,嗯...不要将其设为 const。 const 的目的是告诉编译器您不会更改该值。因此,如果您事后尝试对其进行更改,则违反了 C++ 标准。换句话说,不要这样做!再一次,如果您打算更改一个值,请不要将其设为 const。期间。