![](/img/trans.png)
[英]Converting from "foo<T>" to "const foo<const T>" - C++
[英]How to pointer-cast Foo** to const Foo** in C++
我有
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();
}
如何通過指針廣播實現const Fred ** 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時遇到了問題,因此我不得不執行double靜態強制轉換-重新解釋強制轉換不起作用)。
是否有任何方法可以真正更改a1並“正常”編譯,因此如果沒有優化就無法編譯(因此我超越了優化效果)?
應該這樣做:
Foo** f;
const Foo** cf = const_cast<const Foo**>(f);
這不是一個好主意,因為它違反了類型安全性。 讓我解釋一下原因:
Fred* pFred;
const Fred** ppFred = const_cast<const Fred**>(&p);
*ppFred = new const Fred; // Now pFred points to a const Fred
pFred->some_evil_mutating_method(); // can do, since type of *pFred is non-const!
您需要const_cast
。
你為什么不做:?
const Fred** q1;
*q1 = p1;
還是您想在沒有const_cast的情況下避免違反constness? -不,先生,你不能。
你不應該這樣做。 您不能輕易進行轉換的事實是因為它破壞了常數的正確性(並且您的代碼會執行該正確性)。 使用以上建議,您的代碼將編譯並在常量對象(代碼的最后一行)上調用變異方法。
不建議這樣做,在極少數情況下,甚至可能殺死您的應用程序(一個恆定的全局對象可以存儲在一個只讀的內存頁中),或者使其處於不穩定的狀況(您可以通過以下方式更改對象的內部狀態:常量引用到內部成員元素中,打破了對象不變式)。
關於您的問題: C ++ FAQ Lite [18.17]
您無需對const Fred** q1 = &p1
進行任何強制轉換,因為可以在其聲明中將非const Fred**
直接分配給const Fred** q1
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.