博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
深度剖析右值引用
阅读量:3576 次
发布时间:2019-05-20

本文共 1805 字,大约阅读时间需要 6 分钟。

#include 
#include
#include
#include
class MyString { private: char* _data; size_t _len; void _init_data(const char *s) { std::cout <<"void _init_data(const char *s)"<< std::endl; _data = new char[_len+1]; memcpy(_data, s, _len); _data[_len] = '\0'; } public: MyString() { std::cout <<"MyString()"<< std::endl; _data = NULL; _len = 0; } MyString(const char* p) { std::cout <<"MyString(const char* p)"<< std::endl; _len = strlen (p); _init_data(p); } MyString(const MyString& str) { std::cout <<"MyString(const MyString& str)"<< std::endl; _len = str._len; _init_data(str._data); std::cout << "Copy Constructor is called! source: " << str._data << std::endl; } MyString(MyString&& str) { std::cout <<"MyString(MyString&& str)"<< std::endl; _len = str._len; _data = str._data; str._len = 0; str._data = NULL; } MyString& operator=(MyString&& str) { std::cout <<"MyString& operator=(MyString&& str)"<< std::endl; if (this != &str) { _len = str._len; _data = str._data; str._len = 0; str._data = NULL; } return *this; } MyString& operator=(const MyString& str) { std::cout <<"MyString& operator=(const MyString& str)"<< std::endl; if (this != &str) { _len = str._len; _init_data(str._data); } return *this; } virtual ~MyString() { std::cout <<"virtual ~MyString()" << std::endl; if (_data) free(_data); }};/*template
void swap(T& a, T& b){ T tmp(a); // copy a to tmp a = b; // copy b to a b = tmp; // copy tmp to b std::cout <<"L"<
void 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 std::cout <<"R"<
(a1,a2);}

swap函数两种版本的,函数调用时的细节分析如下:

 

转载地址:http://qvxgj.baihongyu.com/

你可能感兴趣的文章
[LeetCode javaScript] 53.最大子序和
查看>>
[LeetCode javaScript] 101. 对称二叉树
查看>>
[LeetCode javaScript] 860. 柠檬水找零
查看>>
[LeetCode javaScript] 118. 杨辉三角
查看>>
[LeetCode javaScript] 905. 按奇偶校验排序数组
查看>>
[LeetCode javaScript] 617. 合并二叉树
查看>>
[LeetCode javaScript] 292. Nim游戏
查看>>
[LeetCode javaScript] 896. 单调数列
查看>>
[LeetCode javaScript] 804. 唯一摩尔斯密码词
查看>>
[LeetCode javaScript] 476. 数字的补数
查看>>
[LeetCode javaScript] 811. 子域名访问计数
查看>>
[LeetCode javaScript] 414. 第三大的数
查看>>
[LeetCode javaScript] 242. 有效的字母异位词
查看>>
[LeetCode javaScript] 75. 颜色分类
查看>>
[LeetCode javaScript] 56. 合并区间
查看>>
[LeetCode javaScript] 190. 颠倒二进制位
查看>>
[LeetCode javaScript] 521. 最长特殊序列 Ⅰ
查看>>
[LeetCode javaScript] 806. 写字符串需要的行数
查看>>
[LeetCode javaScript] 824. 山羊拉丁文
查看>>
[LeetCode javaScript] 463. 岛屿的周长
查看>>