Redian新闻
>
static initialization dependency c++ (转载)
avatar
static initialization dependency c++ (转载)# JobHunting - 待字闺中
r*u
1
【 以下文字转载自 Programming 讨论区 】
发信人: raou (raou), 信区: Programming
标 题: static initialization dependency c++
发信站: BBS 未名空间站 (Wed Feb 6 13:38:35 2013, 美东)
Here's a common scenario: source file first.cpp define a static data member
of a class and provided an initializer for it. Source file second.cpp #
includes first.h and attempts to examine the value of the static data member
. When you execute that statement, the program crashes.The reason is the
compiler doesn't guarantee that C::i is initialized before it is referenced
in the second.cpp. Here is example:
//----first.h
class C
{
public:
static const int i;
};
//----first.cpp
#include "first.h"
const int C::i=5;
//----second.cpp
#include "first.h"
int MIN=C::i; // may crash here
Questions:
1. Do we have this problem in C too or only in C++? I have never noticed
this problem in C.
2. This seems a pretty serous problem. How to avoid it? E.g., if we use
singleton, how to make sure that the instance is initialized before use it?
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。