在 C++ 中事后添加常量;

发布于 2024-09-19 10:19:13 字数 969 浏览 7 评论 0原文

可能的重复:
是否有一些忍者技巧变量声明后使其常量?

考虑以下最小示例:

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何时共饮酒 2024-09-26 10:19:13

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

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

傲世九天 2024-09-26 10:19:13

怎么样:

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 引用)

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文