一般而言,將T const
轉換爲T
與const_cast<>
幾乎總是不必要的。這是因爲常量對象正在轉換爲非常量臨時對象,並且這可以在沒有強制轉換的情況下安全地完成。
int const n; // n is a constant int
int x = n; // perfectly safe
即使T
是指針類型也是如此。
int * const n; // n is a constant pointer to an int
int * x = n; // perfectly safe
但是,如果移動const
關鍵字前,它不再是使得指針類型不變,但被指向到常量的類型。因此,我們上面的例子:
const int * n; // n is a pointer to a constant int
int * x = n // error, x is a pointer to an int
你可以看到,x
點,比n
點不同的東西,所以初始化失敗。在這種情況下,初始化將需要const_cast<>
:
int * x = const_cast<int *>(n);
// cast away the const-ness that n is pointing to
你只能這樣做,如果你知道n
實際上是modifyable(它可能不是如果指針是實際只讀存儲器),或者如果您知道x
的用戶實際上不會嘗試修改n
指向的內容。
對於你的榜樣,你似乎認爲你const
方法應該返回一個指針,以這樣一種方式,該數據是由調用者修改你的對象保存數據。也就是說,由於n()
方法被聲明爲const
,這意味着被訪問對象的內容應該被視爲常量。因此,n_
是一個常數爲int
的數組,它將衰減爲指向常量int
的指針,但您要返回指向int
的指針。
如果您打算n_
是可修改的,無論該對象是否被視爲常量,您可以使用mutable
聲明該意圖。這將使n_
被視爲非常量,即使包含對象是const
,並且它因此使const_cast
不必要。
class A
{
private:
mutable int n_[10];
public:
/* ... */
int* n() const
{
return n_;
}
};
來源
2015-04-20 19:15:00
jxh
是的,但沒有必要。你沒有返回一個引用,所以調用者無法通過調用'n()'來修改'n_'。 – jxh
當前的代碼試圖返回一個'int *'作爲'int'。 –
現在你允許我這樣做:'const A a; int * p = a.n(); p [0] = 2;'。所以不,它根本就不安全。 – chris