我正在尝试理解这个复制构造函数问题。程序退出后,我的问题与析构函数有关。似乎变量char * title没有被破坏,我认为这可能是错误的,谢谢
另一个问题是当对象x等于x2时,不调用赋值运算符的原因。我正在使用带有代码块的g ++。
#include <iostream>
using namespace std;
class myClass
{
private:
int x;
int *p;
char* title;
public:
myClass(int tx, int* temp, char* newtitle)
{
x = tx;
cout << "int constructor called with value x = " << x << endl;
p = new int;
p = temp;
title = new char [strlen(newtitle)+1];
strcpy(title, newtitle);
}
myClass(const myClass& mc)
{
cout << "copy constructor called with value = " << mc.x << endl;
x = mc.x;
p = new int;
*p = *mc.p;
title = new char [strlen(mc.title)+1];
strcpy(title, mc.title);
}
myClass & operator = (const myClass & that)
{
cout << "assignment called" << endl;
if(this != &that)
{
x = that.x;
}
return *this;
}
~myClass()
{
if (p)
{
cout<<"deleting p"<<endl;
delete p;
}
else if(title)
{
cout<<"deleting title"<<endl;
delete[] title;
}
}
};
int main()
{
int pointee = 10;
int* p = &pointee;
myClass x(3,p,"hello");
//myClass y = myClass(3,p);
myClass x2 = x;
return 0;
}
答案 0 :(得分:3)
您可以在实际代码和常规方法中看到各种各样的问题。
首先,不删除char * title
,因为您不删除它。这可能是一个逻辑错误:
if (p)
{
cout<<"deleting p"<<endl;
delete p;
}
else if(title)
{
cout<<"deleting title"<<endl;
delete[] title;
}
您可能不需要else
。你为什么把它放在那里?
接下来,您正在泄漏int
,此处:
p = new int;
p = temp;
int
只是new
- ed被传入的值temp
覆盖。
稍后,您尝试在析构函数中删除此指针。但是,由于您要删除指向自动变量的指针,因此您将填充堆。这也是一个逻辑错误。解决方案:请勿执行此操作:p = temp;
但最终,你的方法在多个层面上都是有问题的。
int
?只需拥有该班级的int
成员。不要使用动态分配(例如new
和delete
),除非确实必须这样做。char*
动态分配字符串。相反,请使用std::string
#include <string>
std::auto_ptr
的内置#include <memory.h>
,但在其他库中还有许多其他选项,通常是更好的选择。这里流行的是Boost的智能指针。 答案 1 :(得分:1)
如果p
不是p
,您的析构函数会删除NULL
;如果它是非NULL 且title
为NULL ,则删除p
。
但是您的构造函数和复制构造函数始终都会创建new p
和new title
。所以你需要一直检查和删除。
答案 2 :(得分:0)
尝试
*p = *temp;
而不是
p = temp;
并在析构函数中
if(title)
而不是
else if(title)