C++拷贝构造函数、移动构造函数

首先吐槽下,自己一开始搜索的时候,几乎网上所有的都是抄某一个人的,所以自己不得不自己做实验

(1)此时p不是将亡值,所以push_back调用拷贝构造函数

#include  
#include  

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"< v1;
    v1.emplace_back("sunxu",24);  

	vector 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:"<

C++拷贝构造函数、移动构造函数_第1张图片

(2)修改main代码如下:

int main() {
    cout << "emplace_back:" << endl;
    vector v1;
    v1.emplace_back("sunxu",24);  

    vector 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:"<

C++拷贝构造函数、移动构造函数_第2张图片

此时传入的是一个临时对象(将亡值),调用移动构造函数,同时调用析构函数释放临时对象。

(3)接下来考虑扩容问题,修改main如下:

int main() {
    cout << "emplace_back:" << endl;
    vector v1;
    v1.emplace_back("sunxu",24);  

    vector v2;
    cout << "push_back:" << endl;
    //Person p=Person("sunxu1",24);
    //v2.push_back(p);
    cout<<"fisrt push back"<

C++拷贝构造函数、移动构造函数_第3张图片

因为扩容,所以需要拷贝构造之前的元素,调用了对应次数的拷贝构造函数,同时释放之前的资源。但是第三次push_back,因为此时空间可以新增一个元素,所以就没有开辟新内存空间,调用拷贝构造函数并且释放资源。

 

你可能感兴趣的:(C++,c++,拷贝构造函数,移动构造函数)