Let's say I have to read some configuration files to set fields of a structure. As soon as the file has been read and the structure initialized, its field's values should not be changed.
I read many times it was bad to have structures with const fields. But then, how to make sure its fields are not changed ?
Let's come back to the case described above. I have a function supposed to read a file given as argument and instantiate the structure with the values coming from the file. Ideally, this function would return this structure by value. But if I do so with non constant fields, the client can change the values.
A solution would be to have a class to wrap the file reader, with a non const member to the read structure, and a const accessor to read the structure and its fields. But it not very satisfying.
Is there an idiom for this situation?
struct/classwithconstmembers, there are never any absolute rules and sometimes doing something that is usually bad practice can be the right thing in a certain situation. So perhaps just create yourstructwithconstvalues and if it works perfectly for what you need, then don't worry about it.