在C ++中添加const-ness之后的事实

时间:2010-09-15 16:53:35

标签: c++ const const-correctness

  

可能重复:
  Is there some ninja trick to make a variable constant after its declaration?

考虑以下最小例子:

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.
}

目前,我正在做:

namespace
{
  std::string PrepareData(std::string data)
  {
    ::MutateData(data);

    return data;
  }
}

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

在声明之外模拟const有哪些优雅的解决方案?


编辑:我忘了澄清我不能轻松(不是我的代码)更改MutateData

2 个答案:

答案 0 :(得分:2)

您可以使用const引用 请查看http://herbsutter.com/2008,了解其工作原理。

答案 1 :(得分:1)

怎么样:

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

接着是

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

与您所做的不同的是使用const引用,并且只使用一个函数。如果您无法更改MutateData,请执行您的建议(尽管使用const引用)