template<class T>
void swap_elems(T& lhs, T& rhs)
{
    using namespace std;
    cout << " before swap " << endl ;
    lhs.Print() ;
    rhs.Print() ;
    swap(lhs.getptr(), rhs.getptr());
    cout << " after  swap " << endl ;
    lhs.Print() ;
    rhs.Print() ;
}

class A
{
private :
    int* ptr ;
    friend void swap(A& first, A& second) { first.swap(second); }

public:
    A(int i_ = 100)
    {
        ptr = (int*) malloc(sizeof(int)) ;
        *ptr = i_ ;
    }
    void swap(A  other){}
    void call_swap(A&  other)
    {
        swap_elems(*this, other);
    }
    void Print(){ std::cout << *ptr << std::endl ; }
    int*&  getptr()  { return ptr; }
};

int main()
{
    A a1(1000) ;
    A a2(5000) ;
    a1.call_swap(a2) ;
    cout << "after call_swap " << endl ;
    a1.Print() ;
    a2.Print() ;
}

output :

 before swap
1000
5000
 after  swap
5000
1000
after call_swap
5000
1000

 

全站熱搜

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