const-cast

Is this undefined behavior with const_cast? [duplicate]

南笙酒味 提交于 2019-11-26 12:47:28
问题 This question already has an answer here: behavior of const_cast in C++ [duplicate] 3 answers What is happening here? const int a = 0; const int *pa = &a; int *p = const_cast<int*>(pa); *p = 1; // undefined behavior ?? cout << a << *p; // ?? My compiler outputs 0 and 1, but address of \'a\' and value of \'p\' is the same, so I\'m confused how is this possible. 回答1: Quote from cppreference: Even though const_cast may remove constness or volatility from any pointer or reference, using the

Is const_cast safe?

折月煮酒 提交于 2019-11-26 01:28:55
问题 I can\'t find much information on const_cast . The only info I could find (on Stack Overflow) is: The const_cast<>() is used to add/remove const(ness) (or volatile-ness) of a variable. This makes me nervous. Could using a const_cast cause unexpected behavior? If so, what? Alternatively, when is it okay to use const_cast ? 回答1: const_cast is safe only if you're casting a variable that was originally non- const . For example, if you have a function that takes a parameter of a const char * , and