Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: how to deal with const object that needs to be modified?

I have a place in the code that used to say

const myType & myVar = someMethod();

The problem is that:

  • someMethod() returns const myType

  • I need to be able to change myVar later on, by assigning a default value if the object is in an invalid state. So I need to make myVar to be non-const.

    1. I assume I need to make myVar be non-reference as well, right? E.g. myType myVar?

    2. What is the C++ "correct" way of doing this const-to-nonconst? Static cast? Lexical cast? Something else?

I may have access to boost's lexical cast, so I don't mind that option, but I'd prefer the non-boost solution as well if it ends up i'm not allowed to use boost.

Thanks!

like image 832
V_D_R Avatar asked Oct 15 '09 14:10

V_D_R


2 Answers

You probably don't need any cast. If you can copy a T, then you can also copy a T const, pathological cases excluded. The copy of the T const need not be a T const itself.

myType myVar = someMethod(); // Creates a non-const copy that you may change.
like image 130
MSalters Avatar answered Sep 20 '22 07:09

MSalters


I wouldn't use the const_cast solutions, and copying the object might not work. Instead, why not conditionally assign to another const reference? If myVar is valid, assign that. If not, assign the default. Then the code below can use this new const reference. One way to do this is to use the conditional expression:

const myType& myOtherVar = (myVar.isValid() ? myVar : defaultVar);

Another way is to write a function that takes a const reference (myVar) and returns either myVar or defaultVar, depending on the validity of myVar, and assign the return value from that to myOtherVar.

A third way is to use a const pointer, pointing it at either the address of myVar or the address of the default object.

like image 24
divegeek Avatar answered Sep 22 '22 07:09

divegeek