Used before initialized on static member variable

#include <iostream>
using namespace std;

class A
{
public:
    A() { cout <<"A::A()" <<endl; }
    auto foo() -> void
    { cout <<"A::foo(). m_x = " <<m_x <<endl; }

    int m_x = 100;
};

class B
{
public:
    B() { m_a.foo(); }       // Destructive! 'm_a' has not been initialized yet.

    static A m_a;    
};

B g_b;                       // 'B::B()' is called before initialization 
                             // of it's static member('m_a').

A B::m_a;                    // 'm_a' is initialized too late.

int main()
{
    return 0;
}

 

  The two red line in code above is destructive. For when constructing global 'g_b', it's static member variable 'm_a' is not initialized yet, while the m_a is type 'class A', which has a non-trivial contructor.

  Such call like 'm_a.foo()' without initialization of 'm_a' may cause a exception and opaque problem soon or later.

 

Solution:

class B
{
public:
    B()
    {
        bar1().foo();         // 'class A' will be intiialized before used.
        bar2()->foo();        // 'class A' will be intiialized before used.
    }    
    ~B() { delete m_pA; m_pA = NULL; }

    auto bar1() -> A          // Solution 1.
    {
        static A a;
        return a;
    }
    auto bar2() -> A *        // Solution 2.
    {
        static A *m_pA = new A;
        return m_pA;
    }

    //static A m_a;    
    A *m_pA = 0;
};

 

 

posted @ 2012-09-14 09:55  walfud  阅读(212)  评论(0编辑  收藏  举报