zoukankan      html  css  js  c++  java
  • c++ 移动构造函数

    1 c++ 移动构造函数.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;
        }
    };
    
    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(std::move(s1));
    //  cout<<s1<<endl;//s1已经指向nullptr,所以不要被打印,否则结果未知
        cout<<s2<<endl;
        cout<<s3<<endl;
    //  cout<<s1+s2<<endl;
        return 0;
    }
    
  • 相关阅读:
    中美土味摄影联合展览4.0
    计算机系统漫游
    Python连接Redis连接配置
    对kotlin和java中的synchronized的浅谈
    不务正业
    功能性测试分类
    Golang os/exec 实现
    面试研究所
    operator和if结构
    Mechanism for self refresh during C0
  • 原文地址:https://www.cnblogs.com/Sico2Sico/p/5384238.html
Copyright © 2011-2022 走看看