【发布时间】:2013-10-01 12:01:27
【问题描述】:
我有以下类,当调用析构函数并尝试删除指向 a 和 b 的指针时出现错误。看起来它们不存在。 这是触发问题的代码行:
unordered_map<string,Stock>* SDict = new unordered_map<string,S>();
SDict->insert(make_pair("38363",S("38363",i,w)));
标题
class O{
public:
O();
~O();
O(const O& tocopy);
O& operator=(const O& toassign);
private:
unordered_map<int,PQL>* b;
unordered_map<int,PQL>* a;
};
来源
O::O(){
a = new unordered_map<int,PQL>();
b = new unordered_map<int,PQL>();
}
O::~O(){
delete b; //I get the exception here- b doesn't exist before the delete.
delete a;
}
O& O::operator=(const O& src){
if(this != &src){
delete b;
delete a;
b = new unordered_map<int,PQL>();
b = src.b;
a = new unordered_map<int,PQL>();
a = src.a;
}
return *this;
}
O::O(const O& src){
b = new unordered_map<int,PQL>();
b = src.b;
a = new unordered_map<int,PQL>();
a = src.a;
}
PQL 是一个只有三个整数的类。是否有明显的原因导致此错误?
类 O 是以下类的数据成员:
标题
class S{
public:
S();
S(string sid, vector<string>* indexids, vector<double>* sw);
~S();
S(const S& tocopy);
S& operator=(const S& toassign);
private:
string sid;
O* o;
vector<Strategy*> ts;
unordered_map<string,double>* iw;
};
来源
S::S(){}
S::S(string sid, vector<string>* iis, vector<double>* sw){
sid = sid;
iw = new unordered_map<string,double>();
o = new o();
if(iis->size() == sw->size()){
for(size_t i=0; i<iis->size(); i++){
string key = iis->at(i);
if(iw->count(key) == 0 ){
double weighting = sw->at(i);
iw->insert(make_pair(key,weighting));
}
else{
throw new exception();
}
}
}
else{
throw new exception();
}
}
S::S(const S& rhs){
sid = rhs.sid;
ts = rhs.ts;
o = new O();
o = rhs.o;
iw = new unordered_map<string,double>();
iw = rhs.iw;
}
S& S::operator=(const S& src){
if(this != &src){
delete o;
delete iw;
sid = src.sid;
ts = src.ts;
o = new o();
o = src.o;
iw = new unordered_map<string,double>();
iw = src.iw;
}
return *this;
}
S::~S(){
delete o;
delete iw;
}
【问题讨论】:
-
我编辑了我的答案以包括 unordered_map 插入(我认为这是创建一个临时 S 对象,这会导致调用复制构造函数和析构函数。
-
哇,我不记得我是否在我的生活中看到了更多的内存泄漏o_O
-
您的复制构造函数不是复制地图,而是复制指针(并泄漏您刚刚分配的地图)。复制行需要为
b = new unordered_map<int,PQL>(*src.b);(类似更改a的分配)。但是为什么你的类包含指向地图的指针,数据成员应该是unordered_map<int,PQL> b; -
@Everyone-我是一个新手 C++ 程序员,所以欢迎所有有建设性的 cmets
-
Pointers... pointers everywhere. 但说真的,这么多裸指针,甚至不值得修复代码。只需重写所有内容以使用引用、自动变量或
unique_ptr/shared_ptr。
标签: c++ copy destructor copy-constructor deep-copy