[英]static object and member method called before constructor
I have two classes A and B such that A has a static B instance as its member. 我有两个类A和B,这样A就有一个静态B实例作为其成员。 B has a function Show() and here is my class A:
B有一个函数Show(),这是我的类A:
class A
{
A()
{
_b.Show();
}
private:
static B _b;
};
and subsequent code is 而随后的代码是
A a;
B A::_b;
int main()
{
}
Now B::Show() called before B is constructed due to the sequence in which I have defined a and _b. 现在,由于我定义了a和_b的顺序,因此在构造B之前调用了B :: Show()。 But how does this work exactly ie how is it possible to make calls on an object that is still not constructed ?
但是,这到底是如何工作的,即如何对仍未构造的对象进行调用呢?
It's not possible, it's undefined behavior (in this case, because you're accessing an uninitialized object) because a
is initialized before A::_b
. 这是不可能的,这是未定义的行为(在这种情况下,因为您正在访问未初始化的对象),因为
a
在A::_b
之前被初始化。
Look up static initialization order fiasco . 查找静态初始化顺序失败 。 You don't get an error because 99% of the times this happens, it's not easily diagnosable.
您不会收到错误,因为在这种情况下有99%的时间会发生这种情况,因此不容易诊断。
This is the static initialisation order problem. 这是静态初始化顺序问题。 Hard to solve in the general case, but one way to fix some cases is to put the dependency inside a function like this:
在一般情况下很难解决,但是解决某些情况的一种方法是将依赖项放在这样的函数中:
class A
{
public:
A()
{
getB().Show();
}
private:
static B& getB()
{
static B b;
return b;
}
};
statics within functions are guaranteed to be initialised the first time that a call is made to it. 确保函数中的静态函数在首次调用它时进行初始化。 Additionally in C++11 this is guaranteed to be thread safe as well.
此外,在C ++ 11中,这也保证是线程安全的。
Further reading: 进一步阅读:
http://www.parashift.com/c++-faq/static-init-order-on-first-use.html http://www.parashift.com/c++-faq/static-init-order-on-first-use.html
Finding C++ static initialization order problems 查找C ++静态初始化顺序问题
how is it possible to make calls on an object that is still not constructed?
如何对仍未构造的对象进行调用?
Well, the simple answer is, exactly the way that code does it. 好吧,简单的答案就是代码执行的方式。
<g>
. <g>
。 Objects defined at file scope in the same translation unit are constructed in the order in which their definitions occur, so if the constructor of one object relies on another object, you have to ensure that the second object has already been constructed when the constructor for the first object runs. 在同一个翻译单元中在文件范围内定义的对象是按照其定义出现的顺序构造的,因此,如果一个对象的构造函数依赖于另一个对象,则必须确保当第二个对象的构造函数已被构造时,第二个对象已被构造。第一个对象运行。
C++ doesn't offer any help here; C ++在这里没有提供任何帮助。 you have to keep track of it yourself.
您必须自己跟踪它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.