我有代码,其中必须通过相当多的代码设置全局资源:
globalClass foo; // global variable / object; give it a memory space to live
void doSomething( void )
{
foo.bar(); // use the global foo object
}
int main( int argc, const char *argv[] )
{
foo( argc ); // foo can only be instantiated in main as it's using
// information that's only available here
doSomething(); // use the global foo object
return 0;
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,foo具有全局范围 - 但要调用其构造函数,我需要一些仅在其中可用的信息main.
我怎样才能做到这一点?
我能想出的唯一解决方案是创建foo一个指针globalClass- 但是每次我使用时都会导致指针解除引用foo.在紧密循环中使用时,这可能会产生性能问题......
PS:在真正的程序中main,doSomething将生活在不同的文件中.它当然保证foo在实例化之前不会被访问.
如何在函数内部foo作为static变量?这样,它只在调用函数时被实例化:
globalClass& getThing()
{
static globalClass thing;
return thing;
}
void doSomething(const globalClass& thing);
int main()
{
const globalClass& x = getThing();
doSomething(x);
}
Run Code Online (Sandbox Code Playgroud)
如上所述使用指针是最简单,最干净的事情.指针取消引用的开销并不是那么多.除非你真的证明了开销是显而易见的,否则我建议使用它.
您的第二个选择是将构造和初始化globalClass分成两个单独的方法.构造函数只会做最简单的事情,不需要外部信息,你可以打电话init(argc)或其他内部的东西main来合并外部信息.
您还可以使用赋值初始化foo,如:
globalClass foo;
int main(int argc, const char *argv[]) {
globalClass bar(argc);
foo = bar;
}
Run Code Online (Sandbox Code Playgroud)
这主要是使用临时变量进行初始化,然后复制结果.
| 归档时间: |
|
| 查看次数: |
2320 次 |
| 最近记录: |