C++拷贝构造函数、移动构造函数
2021-05-28 16:04
1201 查看
首先吐槽下,自己一开始搜索的时候,几乎网上所有的都是抄某一个人的,所以自己不得不自己做实验
(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,因为此时空间可以新增一个元素,所以就没有开辟新内存空间,调用拷贝构造函数并且释放资源。
相关文章推荐
- C++ 学习笔记(13)拷贝构造函数、拷贝赋值运算符、移动构造函数、移动赋值运算符、析构函数、右值引用、引用限定符
- C++拷贝构造函数和移动构造函数
- c++构造函数,拷贝构造函数,赋值构造函数
- 【C++学习】构造函数、拷贝构造函数、析构函数小结
- C++ 学习总结(十)——C++类与对象,及构造函数,析构函数,拷贝构造函数
- c++中的构造函数和拷贝构造函数
- C++:实例解析构造函数、析构函数、拷贝构造函数等
- C++ 构造函数 析构函数 拷贝构造函数 运算符重载解析。
- C++的6大成员函数,构造函数(初始化列表),析构函数,拷贝构造函数,运算符重载,const成员函数
- c++中的构造函数和拷贝构造函数
- C++什么时候调用拷贝构造函数和什么时候调用构造函数
- c/c++ 构造函数、拷贝构造函数、析构函数和赋值运算符重载
- 关注C++细节——含有本类对象指针的类的构造函数、析构函数、拷贝构造函数、赋值运算符的例子
- C++ 拷贝构造函数 赋值构造函数
- C++中的构造函数,拷贝构造函数和赋值运算
- C++实现一个类并包含构造函数,拷贝构造函数,赋值函数,析构函数
- C++ 拷贝构造函数 赋值构造函数
- 拷贝构造函数和移动构造函数解析
- C++ 拷贝构造函数 赋值构造函数
- C++ 拷贝构造函数 赋值构造函数