Suppose I'm using an external API, and in that API, they define:

const Bar& Foo() const;

So this function returns a Bar by reference.

Now, I have a function

void f()
  Bar P = Foo();

Is it safe to const_cast whatever is returned by Foo? I want to change the object Foo returns, but it returns a const Bar, so the compiler gives me an error. I know I can const_cast, and then everything works (I've tried it), but is it safe? Or should I do something else?


Edited by mike_2000_17: Fixed formatting

8 Years
Discussion Span
Last Post by Xorlium

It should never be considered "safe" to cast away a const, on some platforms const values are actually stored in constant unchangeable memory and trying to alter such a value can produce a processor trap. In fact I can not think of a time when casting away the cost is safe.

If you want to alter the value returned then take a copy of it and alter your copy. This is in fact what your code does since you have declare Bar P rather than Bar& P . You can always copy from a const because (generally) copying a value does not alter it.


Well, I wanted to modify the actual object, not my copy. And I did have Bar &P, I just wrote it wrong when posting here.

I'll have to figure a way around this without using const_cast.


This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.