本文介绍了构造函数之前调用的静态对象和成员方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类A和B,因此A具有一个静态B实例作为其成员。 B有一个函数Show(),这是我的类A:

I have two classes A and B such that A has a static B instance as its member. B has a function Show() and here is my class A:

class A
{
  A()
  {
    _b.Show();
  }
private:

  static B _b;
};

,后续代码为

A a;
B A::_b;

int main()
{
}



a和_b的顺序,因此在构造B之前调用B :: Show()。但是,这到底是如何工作的,即如何对尚未构造的对象进行调用?

Now B::Show() called before B is constructed due to the sequence in which I have defineda and _b. But how does this work exactly i.e. how is it possible to make calls on an object that is still not constructed ?

推荐答案

可能是未定义的行为(在这种情况下,因为您正在访问未初始化的对象),因为 a A :: _ b

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.

查找静态初始化顺序失败。您不会收到任何错误,因为在这种情况下,有99%的情况会发生,这很容易诊断。

Look up static initialization order fiasco. You don't get an error because 99% of the times this happens, it's not easily diagnosable.

这篇关于构造函数之前调用的静态对象和成员方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:42