c++ - 是否有一些忍者技巧可以在声明后将变量设为常量?

标签 c++ c++11 const-correctness

我知道答案是 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/

相关文章:

c++ - 使用 C++ 中的异步接口(interface)连接 Ada

c++ - 分组 QComboBox

c++ - 我可以强制初始化枚举类类/函数模板的所有可能枚举值吗?

c++ - boost::optional 不允许我重新分配 const 值类型

c++ - 在 push_back cin 不起作用之后

c++ - 无法为 Oculus Rift 创建 OpenGL 交换纹理

C++ 运算符 + 和 * 非常量重载

c - 为什么 C 标准库忽略 const 的正确性?

类中的 C++11 静态结构编译,为什么不链接?

c++ - 在 C++ 中,我可以声明一个引用以表明不会修改它吗?