C++11移动构造函数,移动赋值运算符

来源:互联网 发布:七周成为数据分析师13 编辑:程序博客网 时间:2024/05/17 05:05

(图来自互联网)

#include <iostream>class Someclass{private:char * s;public:// 如果手动提供了析构函数,复制构造函数,复制赋值运算符,编译器不自动提供移动构造函数和移动赋值运算符;// 如果手动提供了移动构造函数或移动赋值运算符,编译器奖不会自动提供复制构造函数和复制赋值运算符Someclass();Someclass(const char * _s);Someclass(const Someclass & _sc);Someclass(Someclass && _sc);Someclass & operator=(const Someclass & _sc);Someclass & operator=(Someclass && _sc);~Someclass();public:void Print() const;};Someclass::Someclass() : s(nullptr){}Someclass::Someclass(const Someclass & _sc){std::cout << "copy" << std::endl;s = (char *)malloc(sizeof(char) * (strlen(_sc.s) + 1));strcpy(s, _sc.s);}Someclass::Someclass(Someclass && _sc){std::cout << "copy&&" << std::endl;s = _sc.s;_sc.s = nullptr;}Someclass & Someclass::operator=(const Someclass & _sc){std::cout << "=" << std::endl;if (this == &_sc){return *this;}if (s){free(s);s = nullptr;}s = (char *)malloc(sizeof(char) * (strlen(_sc.s) + 1));strcpy(s, _sc.s);return *this;}Someclass & Someclass::operator=(Someclass && _sc){std::cout << "&&=" << std::endl;if (this == &_sc){return *this;}if (s){free(s);s = nullptr;}s = _sc.s;_sc.s = nullptr;return *this;}Someclass::Someclass(const char * _s){s = (char *)malloc(sizeof(char) * (strlen(_s) + 1));strcpy(s, _s);}void Someclass::Print() const{if (!s)return;std::cout << s << std::endl;}Someclass::~Someclass(){if (s){free(s);std::cout << "~" << std::endl;}}int main(){Someclass sc = "abc";// 隐式调用构造函数Someclass sc2("xxx");sc2 = std::move(sc);// 强制调用移动复制运算符函数,std::move强制转化为右值<pre class="cpp" name="code" snippet_file_name="blog_20160929_1_515207" code_snippet_id="1907750">// 可以理解为同一片堆内容分给了新的对象,旧的对象指向堆的指针设为nullptrsc.Print();// 空的sc2.Print();return 0;}


0 0
原创粉丝点击