拋棄常數
可以使用 const_cast
關鍵字將指向 const 物件的指標轉換為指向非 const 物件的指標。這裡我們使用 const_cast
來呼叫一個不是 const-correct 的函式。它只接受非 const char*
引數,即使它從不通過指標寫入:
void bad_strlen(char*);
const char* s = "hello, world!";
bad_strlen(s); // compile error
bad_strlen(const_cast<char*>(s)); // OK, but it's better to make bad_strlen accept const char*
const_cast
到引用型別可用於將 const 限定的左值轉換為非 const 限定值。
const_cast
很危險,因為它使 C++型別系統無法阻止你嘗試修改 const 物件。這樣做會導致未定義的行為。
const int x = 123;
int& mutable_x = const_cast<int&>(x);
mutable_x = 456; // may compile, but produces *undefined behavior*