gpt4 book ai didi

C++ new() 在调用 ctor 之前崩溃

转载 作者:行者123 更新时间:2023-11-30 02:09:24 29 4
gpt4 key购买 nike

感谢您查看我的问题。

我有一个在我的程序中动态创建的对象。创建是循环的一部分,第一次迭代工作正常。

创建后,我的对象基类将自身添加到 map 中。

这是一些示例代码:

public class Base {  
Base() {
// Add itself to a map
Data::objects[key] = this;
}
}

public class Derived : public Base {
// This ctor only initialize one int field.
Derived() : Base() {};
}

是不是很简单?

在我的代码中,我执行了 Derived * d = new Derived(); 并且由于一些愚蠢的原因,我得到了一个 SIGSEGV。

我尝试调试它,但它在崩溃前甚至没有进入 ctor!

这是我的调用堆栈,因此您可以更好地帮助我:

地址:@0x002c0000
ntdll!RtlReleasePebLock()
地址:@0x0000000c 在 c:...\STL_deque.h:514
msvrct!malloc()
libstdc++-6!_Znwj()
fu87_ZSt4cerr(this=0xbc1ad8, e="//my object name//") at//my object name//.cpp
...其他是我的台词。

谢谢你,迈克尔

{享受}

编辑:添加关于 map 的信息

map 静态地位于数据类中。

// Data.h
class Data {
static map<int, Base*> objects;
}

// Data.cpp
#include "Data.h"
map<int, Base*> Data::objects;

// methods implementations

你怎么能破坏堆,我怎么能发现发生了腐败?

最佳答案

Data::objects 在创建 Base 的任何用法之前是否已初始化?

当你在最终链接目标中有多个翻译单元(读取,.cpp 文件)时,你不能保证类对象 objects 已经被初始化,除非您已付出特别努力来确保它。

大多数人通过使用静态类来解决这个问题,通过静态类可以保证在首次使用时进行初始化。像这样的东西:

// untested code, typed in by hand, not compiled through a machine compiler.
class Base {
public: static addObject(Base* that);
Base::Base() { Base::addObject(this); }
};
class Derived: public Base {
Derived::Derived() {}
};
//
// and in the .CPP for Base
namespace /* hidden */ {
int object_number = 0;
map<int,Base*> *objects = NULL;
}
void Base::addObject(Base* that) {
// TODO: do something to avoid multi-thread issues if that is ever a concern
if (!objects) {
objects = new map<int,Base*>();
}
(*objects)[++object_number] = that;
}

关于C++ new() 在调用 ctor 之前崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5541488/

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