简体   繁体   中英

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM