简体   繁体   中英

Strange issue using RWTValHashMap with g++ on Linux

I am writing a simple test program on Linux system by using g++ 4.3 and Rogue Wave library. The problem that I am facing here is that the following codes can be compiled but it would pop up a segmentation fault on this line when I run it: _aClasses.insertKeyAndValue(100,1000);

When I run the same piece code on a HPUX machine by using aCC compiler. It runs smoothly which makes me confused. Is that because the way that g++ initialize the static variable is different from aCC does? Anyone knows what's going on here? Thanks in advance.

A.hxx

#include <rw/tvhdict.h>
#include <rw/cstring.h>
#include <rw/rwdate.h>
#include <rw/rstream.h>

using namespace std;

class A
{
   public :
     A();
     static void add();
     struct long_hash {
         unsigned long operator() (const long& x) const { return x;};
     };
     struct long_equal {
         RWBoolean operator() (const long& x, const long& y) const { return x==y;};
     };
   private:
     static RWTValHashMap<long, long, long_hash, long_equal> _aClasses;
};

A.cxx

#include "A.hxx"

RWTValHashMap<long, long, A::long_hash, A::long_equal> A::_aClasses;

A::A()
{
    cout<<"init A"<<endl;
}

void A::add()
{
    _aClasses.insertKeyAndValue(100,1000);
}

B.hxx

class B
{
    public:
        B();
};

B.cxx

#include "B.hxx"
#include "A.hxx"

B::B()
{
   A::add();
}

Main.cxx

#include "A.hxx"
#include "B.hxx"

static B c;

int main()  {
    cout<<"main"<<endl;
    return 0;
}

The order of initialization of static members from different translation units (essentially different cpp/cxx files) is not specified . So whether static B c or RWTValHashMap<long, long, A::long_hash, A::long_equal> A::_aClasses will be initialized first can be different for different compilers and may even change when using the same compiler. It was simply luck that your previous compiler always initialized them in the desired order.

A way to avoid this is to use the 'construct on first use idiom'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM