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?


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.