我在 The Code Project 上找到了 this 答案。它涉及一个额外的静态变量,但我相信它比 bradgonesurfing 的答案更可靠。基本上是这样的:
class Foo
{
public:
static int __st_init;
private:
static int static_init(){
/* do whatever is needed at static init time */
return 42;
}
};
int Foo::__st_init = Foo::static_init();
这也意味着,就像 Java 的静态块一样,您不需要实际拥有 class Foo 的实例,这在类可以获取大量数据时很有用,您只需要在之前自动调用一些东西它加载,而不是实例化它的额外实例。您可以测试该确切的代码块。我刚刚编译了它(用 static_init() 的一点输出,并让 main() 打印 Foo::__st_init,只是为了确保),它工作得很好。
$g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.6.1/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.6.1-9ubuntu3' --with-bugurl=file:///usr/share/doc/gcc-4.6/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++,go --prefix=/usr --program-suffix=-4.6 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.6 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-plugin --enable-objc-gc --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.6.1 (Ubuntu/Linaro 4.6.1-9ubuntu3)
编辑:
抱歉,这么晚了,但我测试了bradgonesurfing 提到的内容:
如果你测试它,我在 main 中访问变量“只是为了确保”
您确保变量是可访问的,因此变量将
被初始化,因此 static_init 将被调用。你确定吗
如果您不打印 Foo::__st_init
,则执行
我在 main.cpp 中使用了以下内容:
#include <iostream>
using namespace std;
class Foo
{
public:
static int __st_init;
private:
static int static_init(){
/* do whatever is needed at static init time */
cout << "Hello, World!";
return 42;
}
};
int Foo::__st_init = Foo::static_init();
int main(int argc, char** argv)
{
return 0;
}
我使用g++ ./main.cpp -o main 编译并运行它并收到友好的“Hello,World!”我的控制台上的消息。为了彻底,我也编译了相同的版本,但没有打印并使用g++ ./main.cpp -g -o main编译。然后我用 gdb 运行可执行文件并得到以下结果:
(gdb) break Foo::static_init
Breakpoint 1 at 0x400740: file ./main.cpp, line 12.
(gdb) start
Temporary breakpoint 2 at 0x4006d8: file ./main.cpp, line 19.
Starting program: /home/caleb/Development/test/main-c++
Breakpoint 1, Foo::static_init () at ./main.cpp:12
12 return 42;
(gdb)
这是 g++ 的最新版本输出:g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2