今天做了道笔试题,是一道改错题,错误隐藏的还蛮深,但要是想到深拷贝和浅拷贝,就容易多了。
题目:
#include <vector>
#include <iostream>
using namespace std;
class CDemo
{
public:
CDemo() : str(NULL) {};
~CDemo() { if (str) delete [] str;}
char *str;
};
void main (void)
{
CDemo d1;
d1.str = new char[32];
strcpy (d1.str, "trend micro");
cout << d1.str;
vector<CDemo> *a1 = new vector<CDemo>();
a1->push_back(d1);
delete a1;
}
哪里有问题?
a1->push_back(d1);
这句调用了默认的拷贝构造函数,是浅拷贝,所以有两个str指针指向同一块内存,析构函数调用两次,第二次delete [] str;引起程序崩溃 。
改错:
应自定义拷贝构造函数
#include <vector>
#include <iostream>
#include <string.h>
using namespace std;
class CDemo
{
public:
CDemo(): str(NULL){
}
CDemo(const CDemo& other): str(NULL)
{
if(other.str)
{
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
}
}
CDemo& operator=(const CDemo& other)
{
if(this == &other)
{
return *this;
}
delete [] str;
str = 0;
if(other.str){
str = new char [strlen(other.str) + 1];
strcpy(str, other.str);
}
return *this;
}
~CDemo(){
if(str)
{
delete [] str;
}
}
char *str;
};
int main(void)
{
CDemo d1;
d1.str = new char[32];
strcpy(d1.str, "trend micro");
cout << d1.str;
vector<CDemo> *a1 = new vector<CDemo>
();
a1->push_back(d1);
delete a1;
return 0;
}
总结一下,遇到指针赋值和拷贝的操作,一定要联想到深拷贝和浅拷贝的问题!!!