繁体   English   中英

在Mac OS X上未初始化静态对象

[英]Static object not initialized on Mac OS X

//File A.h containing class A
//DLL or dylib code.
class A {
  //Class methods
  A ()
  {
    count = 5;
  }

  //Append is running fine as it is tested
  A& Append (const A& a)
  {
    //Append operation.
    str = str + a.str;
    return *this;
  }       

  //this is running fine in all other cases except for this static object.
  A& operator= (const A& a)
  {
     //Statement 1
     str = a.str;
     //Problem is faced in the statement 1 on the assignment of str to a.str
     //I forget to add this code.
     count = a.count;
     return *this;
  }

  private:
  std::string str;
  int count;
};

//File B.cpp in some other layer
//When these variables in dylib.
static A obj1;
static A obj2;
static void f ();
static void g ();

//This Initialize is called whenver DLL or dylib is being loaded.
Initialize ()
{
   f();
   g();
}

//Problem faced in a function f
void f ()
{
  A a;

  //Some operation performed on a
  a.Append (GetA("String"));

  //Here I am facing problem of Bad memory access possibly over statement 1.

  obj1 = a;
  //Debugger on Windows showing the member of obj1 initialized, but not on Mac OS X.
}

void g ()
{
  A a;

  //Some operation performed on a

  //Here I am facing problem of Bad memory access possibly over statement 1.
  obj2 = a;
  //Debugger on Windows showing the member of obj1 initialized, but not on Mac OS X.
}

//The application An exe or .app on Mac OS X
int main ()
{
   InitializeApplication ();

   void * handle;
   //Dynamic library is being loaded.
   handle = dlopen("mylib.dylib", RTLD_LAZY);

   //Functions are being loaded.
   f1  = dlsym(handle, "MyFunction");

    //Rest of the code.

}

当我在Windows上运行类似程序(使用cl编译器编译)时,值obj1.count和obj2.count为5(由默认构造函数初始化)。

但是,当我在Mac OS X(使用clang编译器编译)上运行此程序时,obj1.count和obj2.count的值为0。

我缺少初始化类的静态对象的东西吗? 如果有阵列,需要执行哪些步骤?

在我的程序中,有一个应用程序在加载dylib(在Mac OS X上)或DLL(在Windows上)。 此代码是共享库或DLL的一部分。

静态对象obj1和obj2在DLL中。 此DLL被加载,然后调用。

在Windows中观察到以下行为

  1. 击中放置在obj1和obj2的静态类声明中的断点。
  2. obj1和obj2的对象已正确初始化。
  3. 放在构造函数中的断点也被命中。

在Mac OS X上

  1. 由于此静态声明,因此未命中声明和构造函数中的断点。
  2. 对象obj1和obj2未初始化。

在Mac OS X上,对象中的所有内容均由零初始化。 每个地址均为NULL。

但是,当我将这些变量移到静态库(此dylib链接到该静态库)时,一切都按照预期运行。

dylib中是否存在全局/静态对象问题?

由于您:

  A& operator= (const A& a)
  {
     //Statement 1
     str = a.str;
  }

不复制count ,那么我们可以期望复制对象中count “不确定”值。 诅咒可能是5 ,但还有其他一些价值。 operator=应该复制(或初始化)该类的所有内容。

编辑:并且您应该有return *this; 也在那里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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