我知道答案是 99.99% 否,但我认为值得一试,你永远不会知道。
void SomeFunction(int a)
{
// Here some processing happens on a, for example:
a *= 50;
a %= 10;
if(example())
a = 0;
// From this point on I want to make "a" const; I don't want to allow
// any code past this comment to modify it in any way.
}
我可以用 const int b = a;
做一些类似的事情,但实际上并不相同,而且会造成很多困惑。仅 C++0x 的解决方案是可以接受的。
编辑:另一个不那么抽象的例子,让我问这个问题的例子:
void OpenFile(string path)
{
boost::to_lower(path);
// I want path to be constant now
ifstream ...
}
编辑:另一个具体的例子:Recapture const-ness on variables in a parallel section .
最佳答案
一种解决方案是将所有突变代码分解为 lambda 表达式。执行 lambda 表达式中的所有突变,并将结果分配给方法范围内的 const int
。例如
void SomeFunction(const int p1) {
auto calcA = [&]() {
int a = p1;
a *= 50;
a %= 10;
if(example())
a = 0;
..
return a;
};
const int a = calcA();
...
}
甚至
void SomeFunction(const int p1) {
const int a = [&]() {
int a = p1;
a *= 50;
a %= 10;
if(example())
a = 0;
..
return a;
}();
...
}
关于c++ - 是否有一些忍者技巧可以在声明后将变量设为常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3669315/