c++中在有限范围内赋值的const变量的使用

Use of const variables that are assigned within a limited scope in C++

本文关键字:const 变量 赋值 范围内 c++      更新时间:2023-10-16

我发现自己在两种最佳实践之间存在冲突,我想知道是否有一种方法可以获得两全其美。

我需要从一个坐标系统的选择中得到一个输出,我想做的是:

// PSEUDO-CODE
const my_class& loads_global();
const my_class& loads_local();
GetLoads(COORDINATES coordinates)
{
    switch (coordinates)
    {
    case LOCAL:
        const my_class& loads = loads_local();
        break;
    case GLOBAL:
        const my_class& loads = loads_global();
        break;
    // etc.
    }
    loads.write();
}

使用const引用对性能有好处(这段代码调用了很多),但是如果它是const,它就不能像switch语句或if语句(或者实际上是try语句,我以前想这样做)那样在作用域分隔符中设置。

我可以写load .write();语句,但在实践中它不只是一行,我讨厌重复的代码。我也可以使用指针代替引用("const my_class* const my_object"范例),但这确实使代码看起来比使用引用混乱得多。

是否有一种方法可以在周围的代码中使用const引用,或者分配给一个我不会/不能修改的const变量?

如果你使用c++ 11,你可以使用lambda来隐藏初始化:

GetLoads(COORDINATES coordinates)
{
    const my_class& loads = [&]() -> const my_class& {
      switch (coordinates)
      {
      case LOCAL:
          return loads_local();
          break;
      case GLOBAL:
          return loads_global();
          break;
      default:
          throw something;
      }
    }();  // Note the call operator here!
    loads.write();
}

您可以有第三个函数返回const my_class&并进行切换:

const my_class& loads_global();
const my_class& loads_local();
const my_class& GetLoads(COORDINATES coordinates)
{
    switch (coordinates)
    {
    case LOCAL:
        return loads_local();
    case GLOBAL:
        return loads_global();
    }
}
void DoSomething(COORDINATES coordinates)
{
    const my_class& variable = GetLoads(coordinates);
    variable.write();
}

这个怎么样

const my_class& loads = (coordinates == LOCAL) ? loads_local() : loads_global();

刚好在switch块之前?

对于给定的代码,为什么不如下:

GetLoads(COORDINATES coordinates)
{
    switch (coordinates)
    {
    case LOCAL:
        loads_local().write();
        break;
    case GLOBAL:
        loads_global().write();
        break;
    }
}

不是最花哨的,但它完全避开了局部变量的问题。好吧,你仍然有临时的,但这是不可避免的。