c 或 c++ 中的静态块是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3370004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is static block in c or c++?
提问by Abhineet
I want to know that what is static block in c or c++ with an example? I know what is static but what is the difference between static and static block?
我想通过一个例子知道什么是 c 或 c++ 中的静态块?我知道什么是静态但静态块和静态块有什么区别?
回答by bradgonesurfing
Another alternative is that you might be looking for the analogy of a static block in Java. A block of code that is run when the application is loaded. There is no such thing in C++ but it can be faked by using the constructor of a static object.
另一种选择是您可能正在寻找 Java 中静态块的类比。加载应用程序时运行的代码块。C++ 中没有这样的东西,但可以通过使用静态对象的构造函数来伪造它。
foo.cpp:
struct StaticBlock {
StaticBlock(){
cout << "hello" << endl;
}
}
static StaticBlock staticBlock;
void main(int, char * args[]){
}
HOWEVER. I've been bitten by this before as it's a subtle edge case of the C++ standard. If the static object is not reachable by any code called by main the constructor of the static object may or may not be called.
然而。我以前被这个咬过,因为它是 C++ 标准的一个微妙的边缘情况。如果 main 调用的任何代码都无法访问静态对象,则可能会或可能不会调用静态对象的构造函数。
I found that with gcc hello will get output and with visual studio it will not.
我发现使用 gcc hello 会得到输出,而使用 Visual Studio 则不会。
回答by Caleb1994
I found thisanswer on The Code Project. It involves having an extra static variable, but I believe it is more reliable than bradgonesurfing's answer. Basically, it is 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();
It also means that, like Java's static blocks, you are not required to ever actually have an instance of class Foo
, which is useful when the class can take a lot of data, and you simply need to automagically call something before it loads, not instantiate an extra instance of it. You can test that exact code block. I just compiled it (with a little output from static_init(), and had main() print Foo::__st_init, just to make sure), and it worked just fine.
这也意味着,就像 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)
EDIT:
编辑:
Sorry that this is so late, but I tested what bradgonesurfingmentioned:
抱歉,这么晚了,但我测试了bradgonesurfing提到的内容:
If you test it my accessing the variable in main "just to make sure" you are ensuring the variable is reachable and thus the variable will be initialized and thus static_init will be called. Are you sure it executes if you dont print Foo::__st_init
如果你测试它我访问 main 中的变量“只是为了确保”你确保变量是可访问的,因此变量将被初始化,因此 static_init 将被调用。如果您不打印 Foo::__st_init,您确定它会执行吗
I used the following inside main.cpp:
我在 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;
}
I compiled with g++ ./main.cpp -o main
and ran it and recieved a friendly "Hello, World!" message on my console. Just to be thorough, I also compiled the same version but without the printing and compiled with g++ ./main.cpp -g -o main
. I then ran the executable with gdb and had the following result:
我编译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)
Here's a more current version output for g++: g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
这是 g++ 的最新版本输出: g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
回答by Nordic Mainframe
There is no concept with the name "static block" in C/C++. Java has it however, a "static block" is an initializer code block for a class which runs exactly once, before the first instance of a class is created. The basic concept 'stuff that runs exactly once' can simulated in C/C++ with a static variable, for example:
C/C++ 中没有名为“静态块”的概念。然而,Java 有它,“静态块”是一个类的初始化代码块,在创建类的第一个实例之前,它只运行一次。基本概念“只运行一次的东西”可以在 C/C++ 中使用静态变量进行模拟,例如:
int some_function(int a, int b)
{
static bool once=true;
if (once)
{
// this code path runs only once in the program's lifetime
once=false;
}
...
}
This is not thread-safe however. Getting this working right in the presence of multiple threads can be difficult and tricky sometimes.
然而,这不是线程安全的。在存在多个线程的情况下使这项工作正常进行有时可能很困难也很棘手。
回答by bradgonesurfing
In C++ there is the concept of an anonymous namespace.
在 C++ 中有匿名命名空间的概念。
foo.cpp:
namespace {
int x;
int y;
}
to get the same effect in C
在 C 中获得相同的效果
foo.cpp:
static int x;
static int y;
In simple terms the compiler does not export symbols from translation units when they are either declared static or in an anonymous namespace.
简而言之,当它们被声明为静态或匿名命名空间时,编译器不会从翻译单元导出符号。
回答by einpoklum
While indeed, C++ does not have static blocks as part of the language, you canimplement static blocks without you (as a user) having to use any classes or namespaces, and can write:
虽然确实,C++ 没有静态块作为语言的一部分,但您可以实现静态块,而您(作为用户)不必使用任何类或命名空间,并且可以编写:
#include "static_block.h"
static_block {
int x = 1;
int y = 2;
int z = x+y;
std::cout << z << " = " << x " << " + " << y << "\n";
}
or whatever else you want. You can't have those within classes, though, just at file scope. See a detailed description of these in my answerto a related question, and the code for static_block.h
here.
或任何你想要的。但是,您不能在类中使用它们,只能在文件范围内使用。请参阅我对相关问题的回答中对这些的详细说明,以及static_block.h
此处的代码。
Note:This does not require C++11 and will work well with old compilers.
注意:这不需要 C++11,并且可以很好地与旧编译器配合使用。