views:

96

answers:

2

Possible Duplicate:
Is there some ninja trick to make a variable constant after its declaration?

Consider the following minimal example:

void MutateData(std::string&);

int main()
{
  std::string data = "something that makes sense to humans.";

  ::MutateData(data); // Mutates 'data' -- e.g., only changes the order of the characters.

  // At this point, 'data' should never be changed.
  // Mixing the above with const-correct code seems ugly.
}

Currently, I'm 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 solutions to simulating const beyond the point of declaration?


EDIT: I forgot to clarify that I can't easily (not my code) change MutateData.

+1  A: 

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 the const reference though)

Alexandre C.
There is no clear advantage I can think of in using a constant reference compared to a real variable. In the case of a variable, most compilers will elide the extra copy and build the return object in place. In the reference version, the compiler still needs to keep the temporary (reserve the space in the stack where the return value was created) and possibly create a reference (or avoid creating it, since a reference is an alias it need not create one but just use the identifier to refer to the temporary, which is exactly what the return value optimization would do).
David Rodríguez - dribeas
@David: You're of course right, both are exactly equivalent. But the const reference trick is quite idiomatic...
Alexandre C.
+2  A: 

You can use a const reference.
Take a look at http://herbsutter.com/2008 for an explanation about why it works.

Ugo