Minteh
Minteh

Reputation: 85

Is it allowed to static_cast between different types of const?

I have rarely seen static_cast between top level const so far.
Recently I had to use static_cast to display address of a pointer to const object and I come out with this question:
Is it allowed to static_cast between different types of const?

It passed compilation using gcc 4.7. But I am just asking here to confirm it is not UB. Thanks.

  const int a = 42; // test case 1, const obj
  const double b = static_cast<const double>(a);
  cout << b << endl;


  const int c = 0; // test case 2, pointer to const obj
  cout << static_cast<const void*>(&c) << endl;

Upvotes: 3

Views: 3892

Answers (1)

user657267
user657267

Reputation: 20990

From [expr.static.cast]

[...] The static_cast operator shall not cast away constness

It's perfectly fine to add const using static_cast, then again you don't need to in your test case

const int a = 42; // test case 1, const obj
const double b = static_cast<double>(a); // Works just as well.
const double b = a; // Of course this is fine too

I suppose one of the few times you'd want to add const with static_cast would be to explicitly call an overloaded function

void foo(int*) { }
void foo(int const*) { }

int main()
{
  int a = 42;

  foo(&a);
  foo(static_cast<int const*>(&a));
}

Although with properly designed code you shouldn't really need to do this.

Upvotes: 5

Related Questions