Adding a constant after the fact in C ++

Possible duplicate:
Is there any ninja trick to make a variable constant after declaring it?

Consider the following minimal example:

void MutateData(std::string&); int main() { std::string data = "something that makes sense to humans."; ::MutateData(data); // Mutates 'data' -- eg, only changes the order of the characters. // At this point, 'data' should never be changed. // Mixing the above with const-correct code seems ugly. } 

I am currently doing:

 namespace { std::string PrepareData(std::string data) { ::MutateData(data); return data; } } int main() { const std::string data = ::PrepareData("something that makes sense to humans."); } 

What are some elegant const modeling solutions outside of the declaration?


EDIT: I forgot to make it clear that I cannot easily (not my code) modify MutateData .

+4
source share
2 answers

What about:

 string MakeData(string const&) { ... return string(...); // for return value optimization } 

followed by

 int main() { string const& str = MakeData("Something that makes sense to humans"); } 

The difference with what you do is using a const reference and only one function. If you cannot change MutateData , do what you suggested (with a constant reference)

+1
source

You can use a constant link.
Take a look at http://herbsutter.com/2008 for an explanation of why it works.

+2
source

All Articles