C++拷贝构造函数、移动构造函数
程序员文章站
2022-03-22 21:19:40
...
首先吐槽下,自己一开始搜索的时候,几乎网上所有的都是抄某一个人的,所以自己不得不自己做实验
(1)此时p不是将亡值,所以push_back调用拷贝构造函数
#include <vector>
#include <iostream>
using namespace std;
class Person {
public:
Person(string name,int age):name(name),age(age){
cout << "I have been created" << endl;
}
Person(const Person &p):name(p.name),age(p.age) {
cout << "I have been copy created" << endl;
}
Person(Person &&p) :name(p.name),age(p.age) {
cout << "I have been moved" << endl;
}
~Person() {
cout<<"I have been destroyed"<<endl;
}
private:
string name;
int age;
};
int main()
{
cout << "emplace_back:" << endl;
vector<Person> v1;
v1.emplace_back("sunxu",24);
vector<Person> v2;
cout << "push_back:" << endl;
Person p=Person("sunxu1",24);
v2.push_back(p);
//v1.push_back(Person("sunxu2",24));
//v1.push_back(Person("sunxu2",24));
//v1.push_back(Person("sunxu2",24));
cout<<"destroy:"<<endl;
return 0;
}
(2)修改main代码如下:
int main() {
cout << "emplace_back:" << endl;
vector<Person> v1;
v1.emplace_back("sunxu",24);
vector<Person> v2;
cout << "push_back:" << endl;
//Person p=Person("sunxu1",24);
//v2.push_back(p);
v2.push_back(Person("sunxu2",24));
//v1.push_back(Person("sunxu2",24));
//v1.push_back(Person("sunxu2",24));
cout<<"destroy:"<<endl;
return 0;
}
此时传入的是一个临时对象(将亡值),调用移动构造函数,同时调用析构函数释放临时对象。
(3)接下来考虑扩容问题,修改main如下:
int main() {
cout << "emplace_back:" << endl;
vector<Person> v1;
v1.emplace_back("sunxu",24);
vector<Person> v2;
cout << "push_back:" << endl;
//Person p=Person("sunxu1",24);
//v2.push_back(p);
cout<<"fisrt push back"<<endl;
v1.push_back(Person("sunxu2",24));
cout<<"second push back"<<endl;
v1.push_back(Person("sunxu2",24));
cout<<"third push back"<<endl;
v1.push_back(Person("sunxu2",24));
cout<<"destroy:"<<endl;
return 0;
}
因为扩容,所以需要拷贝构造之前的元素,调用了对应次数的拷贝构造函数,同时释放之前的资源。但是第三次push_back,因为此时空间可以新增一个元素,所以就没有开辟新内存空间,调用拷贝构造函数并且释放资源。