试试下面这段代码的输出是什么?
#include
#include
#include
class foo
{
public:
foo()
{
printf( "before sleep\n" );
Sleep( 1000 );
printf( "after sleep\n" );
}
void test()
{
printf( "in test\n" );
}
};
foo* bar()
{
static foo a;
return &a;
}
unsigned __stdcall thread( void* )
{
foo* p = bar();
p->test();
return 0;
}
int _cdecl main( int argc, char** argv )
{
for( int i = 0; i
不知道C/C++标准有什么规定没有, 但粗看起来好像是编译器的问题呀。我用的是vc8,谁帮忙测测别的编译器。
根据星星的建议,把输出贴出来,如下:
before sleep
in test
in test
in test
in test
in test
in test
in test
in test
in test
after sleep
in test
这里的问题是至少有10个中的9个线程没有等对象初始化完成,就已经调用对象的方法了,这肯定是不对的。我大概看了一下反汇编的结果,实际上还可能出现构造函数被调用多次的情况。
要解决这个问题,在编译器的层次上要容易一点。如果是在用户程序的层次上,则麻烦的多,因为这类方法都会涉及到另一个静态变量的初始化。
卓航论坛免责声明
Discuz X 最新常见问题解决方案
https://bbs.piaoxian.net/thread-77402-1-1.html
(出处: 飘仙建站论坛)