c++中在有限范围内赋值的const变量的使用
Use of const variables that are assigned within a limited scope in C++
我发现自己在两种最佳实践之间存在冲突,我想知道是否有一种方法可以获得两全其美。
我需要从一个坐标系统的选择中得到一个输出,我想做的是:
// 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;
}
}
不是最花哨的,但它完全避开了局部变量的问题。好吧,你仍然有临时的,但这是不可避免的。
相关文章:
- 在内存不足之前,我可以声明多少个 const 变量?
- 当设置为 const 变量时使用 nullptr
- 声明与 const 变量和成员函数相同的标识符
- const变量是否可以在具有默认值的参数中赋值(作为可选参数)
- 编译器在传递 const 变量时返回错误:模板参数不是常量表达式
- 在成员函数之间传递const变量为数组的索引
- 为什么静态常量字符 * const 变量在为左值时可绑定到右值引用参数
- C 编译器可以执行用于返回值的命名const变量的RVO
- 如何访问一系列const变量作为const数组
- C 错误C3892:您无法分配const变量
- 是否可以在C++中推迟 const 变量的初始化,例如 Java 的"blank final"功能?
- 为什么将FMTFLAG指定两次 - 作为枚举的一部分,而另一个实例为静态const变量
- 使用非const变量代替所需的const变量(C )
- 使用const变量时,非静态数据成员的使用无效
- 定义,初始化全局const变量是安全的吗?
- const vs non-const变量一旦分配就没有变化
- 为什么设置const变量(将以相同的值存储)会导致不同的结果
- CPP中的私有静态常规成员变量与const变量
- 在避免新分配的同时,const变量的复杂初始化
- 如何通过其地址更改const变量的值