在 C++ 中事后添加常量;
可能的重复:
是否有一些忍者技巧变量声明后使其常量?
考虑以下最小示例:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 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.
怎么样:
后跟 与
您所做的不同之处在于使用 const 引用,并且仅使用一个函数。如果您无法更改
MutateData
,请按照您的建议进行操作(尽管使用 const 引用)What about:
followed by
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)