zoukankan      html  css  js  c++  java
  • C++ 移动赋值运算符

    1移动赋值运算符.cpp

    #include<iostream>
    #include<string.h>
    using namespace std;
    
    class my_string{
        char* p=nullptr;
        public:
        my_string(){}
        my_string(const char* s){
            if(s){
                p = new char[strlen(s)+1];
                strcpy(p,s);
            }
        }
        my_string( const my_string& ms){
            cout<<"copy construction"<<endl;
            if(ms.p){
                if(p)delete []p;
                p = new char[ms.size()+1];
                strcpy(p,ms.p);
            }
        }
        ~my_string(){
            if(p)delete [] p;
        }
        my_string(my_string && s)
        {
            cout<<"move construction"<<endl;
            p = s.p;
            s.p =nullptr;
        }
    friend ostream &operator<<(ostream&cout,my_string s);
        char & operator[](int pos)
        {
            return p[pos];
        }
        int size()const{return strlen(p);}
        my_string operator+(my_string &s)
        {
            my_string tmp;
            tmp.p= new char[this->size()+s.size()+1];
            strcpy(tmp.p,this->p);
            strcat(tmp.p,s.p);
            return tmp;
        }
        my_string operator+(const char* s)
        {
            my_string tmp;
            tmp.p= new char[this->size()+strlen(s)+1];
            strcpy(tmp.p,this->p);
            strcat(tmp.p,s);
            return tmp;
        }
        my_string &operator=(my_string &&s)
        {
            cout<<"move assignment=(&&)"<<endl;
            p = s.p;
            s.p =nullptr;
    
        }
    };
    
    ostream &operator<<(ostream&cout,my_string s)
    {
        cout<<s.p;
        return cout;
    }
    
    int main()
    {
        my_string s1="123";
        my_string s2="456";
        my_string s3;
        //不要把一个左值轻易转换为右值使用,除非你确定它在下面不再被使用
    //err:  my_string s4(std::move(s1));
    
        //移动赋值运算,提高了运算效率,没有拷贝的过程
        s3 =s1+s2;
        //(a=b)=c;
        int a=1,b=1,c=1;
        (a=b)=c;
        return 0;
    }
    
  • 相关阅读:
    scrapy的自动限速(AutoThrottle)扩展
    js可以控制文件上传的速度吗?
    用DataReader 分页与几种传统的分页方法的比较
    jdbc分页查询
    几种分页方式分析.
    mybatis下的分页,支持所有的数据库
    java 物理分页和逻辑分页
    IBatis的分页研究
    JDBC分页
    用Java实现异构数据库的高效通用分页查询功能
  • 原文地址:https://www.cnblogs.com/Sico2Sico/p/5384237.html
Copyright © 2011-2022 走看看