MyClass.h

#include <iostream>
#include <string>
#include <stdio.h>
#include <memory>
#include <stdexcept>

using namespace std ;

class MyClassImp;

class MyClass
{
public:
    MyClass (); //constructor
    MyClass (const MyClass &my) ;
    MyClass& operator=(const MyClass &rhs) ;
    MyClass (const MyClass &&my) ;
    MyClass& operator=(const MyClass &&rhs) ;
    ~MyClass();
    void  Public_Method();
private:
    shared_ptr<MyClassImp> pimpl_;
} ;

 

MyClass.cpp

#include "MyClass.h"

class MyClassImp
{
public:
   static void   Private_Method(){
       cout << private_var_ << " MyClassImp.Private_Method called " << endl ;
   }
   static  int    private_var_;
} ;
int MyClassImp::private_var_ = 0 ;

MyClass::MyClass()  :  pimpl_( make_shared<MyClassImp>() )
{
    cout << "default cons " << endl ;
}
MyClass::MyClass(const MyClass &my): pimpl_( make_shared<MyClassImp>( *(my.pimpl_)) )
{
    cout << "copy cons " << endl ;
}
MyClass &MyClass::operator=(const MyClass &rhs)
{
    cout << "copy assignment " << endl ;

    pimpl_ = make_shared<MyClassImp>( *(rhs.pimpl_)) ;
    return *this ;
}
MyClass::MyClass(const MyClass &&my): pimpl_( my.pimpl_ )                             
{
    cout << "move cons  " << endl ;
}
MyClass &MyClass::operator=(const MyClass &&rhs)
{
    cout << "move assignment  " << endl ;

    pimpl_ = rhs.pimpl_ ;
    return *this ;
}

MyClass::~MyClass()
{
    ;
}
void   MyClass::Public_Method()
{
    ++pimpl_->private_var_  ;
    pimpl_->Private_Method();
}

MyMain.cpp

#include "MyClass.h"

using namespace std ;

void DoTest1(MyClass  my)
{
    my.Public_Method();
}

int main()
{
    MyClass my ;
    my.Public_Method();
    DoTest1(my) ;
    DoTest1(my) ;
    my.Public_Method();
    cout << "=========================" << endl ;
    MyClass my2 = my ;
    my2.Public_Method();
    my.Public_Method();
    cout << "=========================" << endl ;
    MyClass my3 ;
    my3 = my2 ;
    my3.Public_Method();
    my2.Public_Method();
    cout << "=========================" << endl ;
    MyClass my4 = std::move(my3) ;
    my4.Public_Method();
    cout << "=========================" << endl ;
    MyClass my5  ;
    my5 = std::move(my4) ;
    my5.Public_Method();
}

[impl]$ g++ --std=c++0x MyMain.cpp MyClass.cpp -o MyMain.exe
[impl]$ ./MyMain.exe
default cons
1 MyClassImp.Private_Method called
copy cons
2 MyClassImp.Private_Method called
copy cons
3 MyClassImp.Private_Method called
4 MyClassImp.Private_Method called
=========================
copy cons
5 MyClassImp.Private_Method called
6 MyClassImp.Private_Method called
=========================
default cons
copy assignment
7 MyClassImp.Private_Method called
8 MyClassImp.Private_Method called
=========================
move cons  
9 MyClassImp.Private_Method called
=========================
default cons
move assignment  
10 MyClassImp.Private_Method called

創作者介紹
創作者 hedgezzz 的頭像
hedgezzz

hedgezzz的部落格

hedgezzz 發表在 痞客邦 留言(0) 人氣()