मुझे यकीन है कि निम्नलिखित कोड संकलित नहीं होना चाहिए। लेकिन, जी ++ में, यह संकलित करता है! इसे http://codepad.org/MR7Dsvlz पर संकलित देखें।अमान्य सी ++ से (पॉइंटर से कॉन्स्ट) (पॉइंटर से गैर-कॉन्स) तक कास्ट है?
कोड:
#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"
}
त्रुटि में जी ++ इस संकलन के द्वारा है?
यदि आप स्थिरता को दूर करना चाहते हैं (और आपको यकीन है कि इसकी अनुमति है) idiomatic C++ तरीका यह करने के लिए 'const_cast (ptr1)' है - हालांकि सी कास्ट भी काम करेगा, जैसा कि आपने अभी देखा है । –
यह पढ़ने में मददगार है: http://stackoverflow.com/questions/357600/is-const-cast-safe – Pubby