Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- class A {
- public:
- A() {}
- A(string name) : m_name(name) { printName(__PRETTY_FUNCTION__); }
- ~A() { printName(__PRETTY_FUNCTION__); }
- // 拷贝构造函数
- A(const A &other) { m_name += "copy-" + other.m_name; printName(__PRETTY_FUNCTION__); }
- // 赋值运算符
- A& operator=(const A &other) {
- if (this != &other) {
- m_name += "assign-" + other.m_name;
- printName(__PRETTY_FUNCTION__);
- }
- return *this;
- }
- // 移动构造函数
- A(A &&other) { m_name += "move-" + other.m_name; printName(__PRETTY_FUNCTION__); }
- // 移动赋值运算符
- A& operator=(A &&other) {
- if (this != &other) {
- m_name += "moveassign-" + other.m_name;
- printName(__PRETTY_FUNCTION__);
- }
- return *this;
- }
- string m_name;
- private:
- void printName(string funcName) { cout << funcName << " \t" << m_name << endl; }
- };
- int main()
- {
- vector<A> vec;
- vec.reserve(100);
- vec.push_back(string("a1"));
- printf("=============================\n");
- vec.emplace_back(string("a2"));
- printf("=============================\n");
- A *a3 = new A("a3");
- A *a4 = new A("a4");
- A *a5 = new A("a5");
- // 下面调用的拷贝构造函数
- vec.push_back(*a3);
- vec.emplace_back(*a3);
- // 下面2个当A有移动构造函数时,调用A的移动构造函数;否则调用拷贝构造函数
- vec.push_back(std::move(*a4));
- vec.emplace_back(std::move(*a5));
- printf("============ destruct ==============\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement