vector等一系列容器在添加或者插入元素时,都是创建新的实例然后将需要添加的对象进行拷贝,例如push_back()或者insert(),调用的都是类的构造函数 class (class ),默认的直接给对应的成员赋值,对于指针则只会拷贝指针指向的地址,当需要添加的元素析构或者删除后,则会影响容器内的元素。
所以需要重写拷贝构造函数。
A(const A& b) 以及 A& operator=(const A&b),此处必须用引用,否则需要添加临时的类对象,则又会调用默认构造函数,然后析构,然后报错。。。。。
1、浅拷贝
#include<iostream>
#include<vector>
using namespace std;
class test
{
public:
test() :name(NULL) { cout << "调用默认构造"; }; //1、浅拷贝
test(const char*name, const int age)
{
if (this->name != nullptr)
{
delete[] this->name;
this->name = nullptr;
}
this->name = new char[strlen(name) + 1];
//this->name = nullptr;
const int size = strlen(name) + 1;
cout << "大小" << size << "参数 " << name << endl;
// 第二个参数表示目标缓冲区大小,大于或等于源串的长度 + 1(存放结束符'/0')。如果没有第二个参数,就没有方法来保证有效的缓冲区尺寸,
//不然只能假定缓冲足够大来容纳要拷贝的字符串(strcpy函数)。在程序运行时,这将导致不可预料的行为。
cout << "step1" << endl;
//cin.get();
const char* tem = name;
cout << sizeof(name)<< endl;
strcpy_s(this->name,size , tem);
//memcpy_s(this->name, size,name,size);
//*this->name = *name;
cout << "step2" << endl;
this->age = age;
};
2、拷贝构造(深拷贝)
//修改 拷贝构造(2、深拷贝)
test(const test &t1)
{
if (this->name != nullptr)
{
cout << "此时需要释放name" << this->age<<endl;
delete [ ] this->name;
this->name = nullptr;
}
cout << "此时name: " << t1.name << "age: " << t1.age <<endl;
this->name = new char[strlen(t1.name) + 1];
const int size = strlen(t1.name) + 1;
cout << "此时拷贝构造对象的大小: " <<size<< endl;
cout << "this->name_size:" << sizeof(this->name) << endl;
strcpy_s(this->name, size, t1.name);
this->age = t1.age;
};
test& operator=(const test &t1)
{
if (this->name != nullptr)
{
delete[] this->name;
this->name = nullptr;
}
cout << "此时name: " << t1.name << "age:" << t1.age << endl;
this->name = new char[strlen(t1.name) + 1];
const int size = strlen(t1.name) + 1;
strcpy_s(this->name, size, t1.name);
this->age = t1.age;
return *this;
}
void print()
{
cout << this->name << endl;
}
~test()
{
cout << "尝试调用析构函数" << endl;
if (this->name != nullptr)
{
delete[] this->name;
this->name = nullptr;
}
};
private:
char *name =nullptr;
int age;
};
void main()
{
test t1("kaka",25);
vector<test> v1;
v1.push_back(t1);
t1.~test();
v1.at(0).print();