1

const_cast is safe only if you're casting a variable that was originally non-const.

Are literals the only data that was originally declared as constant? If not can anyone please give example of originally declared const data scenario?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Tahlil
  • 2,680
  • 6
  • 43
  • 84

1 Answers1

4

No, not just literals are originally declared as const. Any object which is declared as const is "originally const".

const int this_is_a_const_int = 10;
const std::string this_is_a_const_string = "this is a const string";

std::string this_is_not_a_const_string;
std::cin >> this_is_not_a_const_string;

const std::string but_this_is = this_is_not_a_const_string;

What's not originally const is when you have a const reference to a non-const object

int n;
std::cin >> n;

const int & const_int_ref = n;
int& int_ref = const_cast<int&>(const_int_ref); // this is safe, because const_int_ref refers to an originally
                                                // non-const int
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • That is what I meant. Objects initialized with literals are originally declared const right? – Tahlil Jun 25 '14 at 04:55
  • 1
    @Tahlil: No. It doesn't matter what it is initialized with. – Benjamin Lindley Jun 25 '14 at 04:55
  • @Tahlil adding to that, it only matters that it *is* initialized (it must be, as it is `const`). Once initialization is finished, `const` is firm. But that much I *think* you already knew. (+1, btw). – WhozCraig Jun 25 '14 at 05:01