Advertisement
devincpp

push_back_vs_emplace_back

Sep 13th, 2023 (edited)
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. class A {
  6. public:
  7.     A() {}
  8.     A(string name) : m_name(name) { printName(__PRETTY_FUNCTION__); }
  9.     ~A() { printName(__PRETTY_FUNCTION__); }
  10.     // 拷贝构造函数
  11.     A(const A &other) { m_name += "copy-" + other.m_name; printName(__PRETTY_FUNCTION__); }
  12.     // 赋值运算符
  13.     A& operator=(const A &other) {
  14.         if (this != &other) {
  15.             m_name += "assign-" + other.m_name;
  16.             printName(__PRETTY_FUNCTION__);
  17.         }
  18.         return *this;
  19.     }
  20.     // 移动构造函数
  21.     A(A &&other) { m_name += "move-" + other.m_name; printName(__PRETTY_FUNCTION__); }
  22.     // 移动赋值运算符
  23.     A& operator=(A &&other) {
  24.         if (this != &other) {
  25.             m_name += "moveassign-" + other.m_name;
  26.             printName(__PRETTY_FUNCTION__);
  27.         }
  28.         return *this;
  29.     }
  30.  
  31.     string m_name;
  32. private:
  33.     void printName(string funcName) { cout << funcName << "  \t" << m_name << endl; }
  34. };
  35.  
  36. int main()
  37. {
  38.     vector<A> vec;
  39.     vec.reserve(100);
  40.  
  41.     vec.push_back(string("a1"));
  42.     printf("=============================\n");
  43.     vec.emplace_back(string("a2"));
  44.     printf("=============================\n");
  45.  
  46.     A *a3 = new A("a3");
  47.     A *a4 = new A("a4");
  48.     A *a5 = new A("a5");
  49.  
  50.     // 下面调用的拷贝构造函数
  51.     vec.push_back(*a3);
  52.     vec.emplace_back(*a3);
  53.  
  54.     // 下面2个当A有移动构造函数时,调用A的移动构造函数;否则调用拷贝构造函数
  55.     vec.push_back(std::move(*a4));
  56.     vec.emplace_back(std::move(*a5));
  57.  
  58.     printf("============ destruct ==============\n");
  59.  
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement