在以下示例中,我正在做 deepcopy,一切正常,但是当 obj2 超出范围时,析构函数正在调用并且它在析构函数内崩溃,所以请帮助我的代码有什么问题:
#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <iostream>
#include <conio.h>
using namespace std;
class ClassA
{
private:
char *str;
int id;
public :
ClassA(int x, char *s)
{
int len = strlen(s)+1;
str = new char[len];
id = x;
strcpy(str, s);
}
~ClassA()
{
delete [] str;
}
ClassA(ClassA &obj)
{
id = obj.id;
int len = strlen(obj.str);
str = new char[len] + 1;
strcpy(str, obj.str + 1);
}
void disply()
{
cout << id << " " << str << endl;
}
};
int main()
{
ClassA Obj1(5, "hello");
{
ClassA Obj2 = Obj1;
Obj2.disply();
}
Obj1.disply();
return 0;
}