Advertisement
devincpp

call_constructor

Sep 13th, 2023 (edited)
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <algorithm>
  5. using namespace std;
  6.  
  7. class A {
  8. public:
  9.     // A() {}
  10.     A(string name) : _name(name) { printName(__PRETTY_FUNCTION__); }
  11.     ~A() { printName(__PRETTY_FUNCTION__); }
  12.     // 拷贝构造函数
  13.     A(const A &other) { _name += ":copyfrom-" + other._name; printName(__PRETTY_FUNCTION__); }
  14.     // 赋值运算符
  15.     A& operator=(const A &other) {
  16.         if (this != &other) {
  17.             _name += ":assignfrom-" + other._name;
  18.             printName(__PRETTY_FUNCTION__);
  19.         }  
  20.         return *this;
  21.     }  
  22.     // 移动构造函数
  23.     A(A &&other) { _name += ":movefrom-" + other._name; printName(__PRETTY_FUNCTION__); }
  24.     // 移动赋值运算符
  25.     A& operator=(A &&other) {
  26.         if (this != &other) {
  27.             _name += ":moveassignfrom-" + other._name;
  28.             printName(__PRETTY_FUNCTION__);
  29.         }  
  30.         return *this;
  31.     }  
  32.  
  33.     string _name = "anno";
  34.  
  35. private:
  36.     void printName(string funcName) { cout << _name << "\t" << funcName << endl; }
  37. };
  38.  
  39. int main()
  40. {
  41.     std::vector<A> vec {std::string("22"), std::string("11")};
  42.  
  43.     std::cout << "sort begin==================\n";
  44.     std::sort(vec.begin(), vec.end(), [](const A& lhs, const A& rhs) {
  45.         return lhs._name < rhs._name;
  46.     });
  47.  
  48.     std::cout << "sort end==================\n";
  49.     for (const auto &ele : vec) {
  50.         std::cout << ele._name << " ";
  51.     }
  52.  
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement