Make函数将全局变量视为const
C++: Make function treat global variable as const
我有以下设置:
Foo.cpp
class Bar {
public:
inline Bar() : x(0), y(0), z(0) {}
inline Bar(int X, int Y, int Z) : x(X), y(Y), z(Z) {}
const int x, y, z;
};
static Bar globalBar;
static void foo() {
int x = globalBar.x; // the compiler should assume globalBar is const here!
...
}
void almightySetup() {
globalBar = Bar(meaningOfLife(), complexCalc(), magic());
startThread(foo); // foo() will NEVER be called before this point!
// globalBar will NEVER be changed after this point!
}
可以看到,编译器在指定的点假定globalBar
是const
是安全的,因为在设置之后,globalBar
在该点之后将永远不会改变。此外,foo()
在设置之前不会被调用。
但是我怎么才能做到这一点呢?我试过使用const_cast<>
,但不断得到类型错误信息。我一定是做错了什么。这可能吗?
我应该补充一点,我不能随意更改foo
的函数签名
这是一个理论上的例子。我还没有测试过,但是我很想听听c++专家的意见。这能行吗?
static Bar globalBar;
static void foo() {
static const Bar myGlobalBar = globalBar;
int x = myGlobalBar .x; // the compiler should assume globalBar is const here!
...
}
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 当vector是tje全局变量时,c++中vector的内存管理
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 内联函数中具有内部链接的全局变量
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 全局变量 多读取器 一个写入器多线程安全?
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 不同作用域中的静态变量和全局变量
- C++ 在编译时具有函数计算全局变量
- 修改程序的入口点时未调用全局变量的构造函数
- 使用 std::ios_base::Init 正确初始化全局变量
- 为什么我的全局变量似乎没有变化?
- C ++程序如何返回我的数组或写入全局变量
- 为什么我的数组值与此处的全局变量不匹配?
- QT C++中对全局变量的未定义引用
- 跨多个类的全局变量而不会出现重定义错误?
- 如何在另一个类中使用来自主类的全局const int变量
- const强制转换为全局变量,程序崩溃(c++)
- Make函数将全局变量视为const
- 声明const全局变量时需要静态的