gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:37:47 27 4
gpt4 key购买 nike

//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 上,对象中的所有内容都由 Zero 初始化。每个地址都是 NULL。

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

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

最佳答案

因为你的:

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

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

编辑:你也应该有一个 return *this; 在那里。

关于c++ - 静态对象未在 Mac OS X 上初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16396621/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com