c++ - 在 Linux 上使用带有 g++ 的 RWTValHashMap 的奇怪问题

标签 c++ linux g++ rogue-wave

我正在使用 g++ 4.3 和 Rogue Wave 库在 Linux 系统上编写一个简单的测试程序。我在这里面临的问题是可以编译以下代码但是当我运行它时它会在这一行弹出一个段错误: _aClasses.insertKeyAndValue(100,1000);

当我使用 aCC 编译器在 HPUX 机器上运行同一段代码时。它运行顺利,这让我感到困惑。那是因为 g++ 初始化静态变量的方式与 aCC 不同吗?有人知道这里发生了什么吗?提前致谢。

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();
}

主.cxx

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

static B c;

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

最佳答案

来自不同翻译单元(本质上是不同的cpp/cxx文件)的静态成员的初始化顺序是not specified .那么是否static B cRWTValHashMap<long, long, A::long_hash, A::long_equal> A::_aClasses will be initialized first 对于不同的编译器可能不同,甚至可能在使用相同的编译器时发生变化。很幸运,您以前的编译器总是以所需的顺序初始化它们。

避免这种情况的一种方法是使用 'construct on first use idiom'

关于c++ - 在 Linux 上使用带有 g++ 的 RWTValHashMap 的奇怪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14223754/

相关文章:

PHP Mailer 在 Linux 中发送电子邮件太慢

linux - 尝试在 mysqldump 不工作的情况下使用 bash 脚本

c++ - 为什么空数组的大小为 0 而空类的大小不为 0?

c++ - Raspberry Pi 使用 SQLite3 和 SDL2 编译多个 C++ 文件

c++ - return 语句不返回值

c++ - 控制台无响应?

linux - 删除 ls -l 输出中的多个空格

c++ - 第一次使用 boost - 为什么我在构建时不必明确链接到它?

c++ - 命名空间; ')' token 之前的预期不合格 ID;结构的无效使用

c++ - 将程序一的输出作为程序二的输入传递