次のコードはコンパイルしないでください。しかし、g ++では、それはコンパイルします!それはhttp://codepad.org/MR7Dsvlzでコンパイルしてください。(constへのポインタ)から(constへのポインタへの)キャストが無効なC++ですか?
コード:
#include <iostream>
using namespace std;
int main() {
int x = 32 ;
// note: if x is, instead, a const int, the code still compiles,
// but the output is "32".
const int * ptr1 = & x ;
*((int *)ptr1) = 64 ; // questionable cast
cout << x ; // result: "64"
}
はこれをコンパイルすることにより、G ++エラーでますか?
constをキャストしたい場合(そしてあなたが許可していることを確信している)、それを行うための慣用的なC++の方法は 'const_cast(ptr1)'です - あなたが見たようにCのキャストも機能します。 –
これは読むのに役立ちます:http://stackoverflow.com/questions/357600/is-const-cast-safe – Pubby