c++11 6个函数

2016-06-15  本文已影响45人  IamOnelong
#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
上一篇下一篇

猜你喜欢

热点阅读