美文网首页
c++11 6个函数

c++11 6个函数

作者: IamOnelong | 来源:发表于2016-06-15 09:23 被阅读45次
    #include <iostream>
    #include <cstring>
    #define PRINT(msg) do { std::cout << msg << std::endl; } while(0)
    class A {
        public:    
            A(const char *pstr) 
            {       
               PRINT("constructor");    
               m_data = (pstr != nullptr ? strcpy(new char[strlen(pstr) + 1], pstr) : 0);          
         }   
    
         A(const A &a) {
            PRINT("const copy constructor");
            //std::cout << a.m_data << std::endl;
            m_data = (a.m_data != nullptr ? strcpy(new char[strlen(a.m_data) + 1], a.m_data) : 0); 
           //std::cout << m_data << std::endl;
        } 
    
       A(A &a) {
            PRINT("copy constructor");
            m_data = (a.m_data != nullptr ? strcpy(new char[strlen(a.m_data) + 1], a.m_data) : 0);
        } 
    
       A(A &&a) : m_data(a.m_data) { 
           PRINT("move constructor");
            a.m_data = 0;
        }
    
        A &operator =(const A &a) {
            PRINT("copy assigment"); 
           if (this != &a) {
                delete [] m_data;
                m_data = (a.m_data != nullptr ? strcpy(new char[strlen(a.m_data) + 1], a.m_data) : 0);
            }
            return *this;
        } 
    
       A & operator = (A &&a) { 
           PRINT("move assigment");
            if (this != &a) {
                m_data = a.m_data;
                a.m_data = 0;
            } 
           return *this;
        }
    
        ~A()    {
            PRINT("destructor");
            delete [] m_data;
        }
    
    //private:
        char *m_data;
    };
    
    void swap(A &a, A &b) {
        //std::move 强制转换成右值
        A tmp(std::move(a));
        a = std::move(b);
        b = std::move(tmp);
    }
    
    A reA() {
        //std::string t("123");
        //A tmp(t.c_str());
        A tmp("qq");
        return tmp;
    }
    
    void printData(const A &a){
        std::cout << a.m_data << std::endl;
    }
    
    int main(int argc, char **argv, char **env) {
        A a("123"), b("456");
        A c = reA();
        printData(c);
        A d =c;
        std::cout << d.m_data << std::endl;
        swap(a, b);
        std::cout << a.m_data <<"  "<< b.m_data<< std::endl;
        return 0;
    }
    

    打印如下

    constructor
    constructor
    constructor
    qq
    copy constructor
    qq
    move constructor
    move assigment
    move assigment
    destructor
    456  123
    destructor
    destructor
    destructor
    destructor
    

    相关文章

      网友评论

          本文标题:c++11 6个函数

          本文链接:https://www.haomeiwen.com/subject/iyoudttx.html