1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | class MyString { private: char* _data; size_t _len; void _init_data(const char *s) { _data = new char[_len+1]; memcpy(_data, s, _len); _data[_len] = '\0'; } public: MyString() { _data = NULL; _len = 0; } MyString(const char* p) { _len = strlen (p); _init_data(p); } MyString(const MyString& str) { _len = str._len; _init_data(str._data); std::cout << "Copy Constructor is called! source: " << str._data << std::endl; } MyString& operator=(const MyString& str) { if (this != &str) { _len = str._len; _init_data(str._data); } std::cout << "Copy Assignment is called! source: " << str._data << std::endl; return *this; } virtual ~MyString() { if (_data) free(_data); } }; int main() { MyString a; a = MyString("Hello"); std::vector<MyString> vec; vec.push_back(MyString("World")); } |
1 2 | Copy Assignment is called! source: Hello Copy Constructor is called! source: World |
1 2 3 4 5 6 7 | MyString(MyString&& str) { std::cout << "Move Constructor is called! source: " << str._data << std::endl; _len = str._len; _data = str._data; str._len = 0; str._data = NULL; } |
1 2 3 4 5 6 7 8 9 10 | MyString& operator=(MyString&& str) { std::cout << "Move Assignment is called! source: " << str._data << std::endl; if (this != &str) { _len = str._len; _data = str._data; str._len = 0; str._data = NULL; } return *this; } |
1 2 | Move Assignment is called! source: Hello Move Constructor is called! source: World |
1 2 3 4 5 6 7 8 9 10 11 12 13 | void ProcessValue(int& i) { std::cout << "LValue processed: " << i << std::endl; } void ProcessValue(int&& i) { std::cout << "RValue processed: " << i << std::endl; } int main() { int a = 0; ProcessValue(a); ProcessValue(std::move(a)); } |
1 2 | LValue processed: 0 RValue processed: 0 |
1 2 3 4 5 6 | template <class T> swap(T& a, T& b) { T tmp(a); // copy a to tmp a = b; // copy b to a b = tmp; // copy tmp to b } |
1 2 3 4 5 6 | template <class T> swap(T& a, T& b) { T tmp(std::move(a)); // move a to tmp a = std::move(b); // move b to a b = std::move(tmp); // move tmp to b } |
1 2 3 4 5 6 | template <typename T> void forward_value(const T& val) { process_value(val); } template <typename T> void forward_value(T& val) { process_value(val); } |
1 2 3 4 5 | int a = 0; const int &b = 1; forward_value(a); // int& forward_value(b); // const int& forward_value(2); // int& |
1 2 3 | template <typename T> void forward_value(T&& val) { process_value(val); } |
1 2 3 4 5 | int a = 0; const int &b = 1; forward_value(a); // int& forward_value(b); // const int& forward_value(2); // int&& |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |