【发布时间】:2011-08-25 16:26:58
【问题描述】:
我遇到了分段错误,我认为这是由复制构造函数引起的。但是,我在网上的任何地方都找不到这样的例子。我读过浅拷贝和深拷贝,但我不确定这个拷贝属于哪个类别。有人知道吗?
MyObject::MyObject{
lots of things including const and structs, but no pointers
}
MyObject::MyObject( const MyObject& oCopy){
*this = oCopy;//is this deep or shallow?
}
const MyObject& MyObject::operator=(const MyObject& oRhs){
if( this != oRhs ){
members = oRhs.members;
.....//there is a lot of members
}
return *this;
}
MyObject::~MyObject(){
//there is nothing here
}
代码:
const MyObject * mpoOriginal;//this gets initialized in the constructor
int Main(){
mpoOriginal = new MyObject();
return DoSomething();
}
bool DoSomething(){
MyObject *poCopied = new MyObject(*mpoOriginal);//the copy
//lots of stuff going on
delete poCopied;//this causes the crash - can't step into using GDB
return true;
}
编辑:添加 operator= 和构造函数
已解决:树错了树,结果是一个函数在同一个对象上调用了两次 delete
【问题讨论】:
-
operator=(const MyObject&)是什么样的? -
您能否提供一个完整 可编译示例来演示该问题?如果需要,消除“发生的很多事情”,它可能与问题相关,也可能不相关。
-
谁一直支持不合标准的问题?我总是能看到它。有人在尝试快速获得徽章吗?
-
我已经添加了overator=,就像我想发布所有我认为我的雇主不会高兴的代码一样。加上大约 5,000 行
-
5,000 行
operator=!好伤心。那就是你的问题。但是要回答您的原始问题,您的复制构造函数具有赋值运算符的语义,因此要判断它是浅的还是深的,您需要查看赋值运算符代码。但我不认为这是你真正的问题,真正的问题是你的课程一团糟。
标签: c++ segmentation-fault copy-constructor deep-copy shallow-copy