0

我在 g++ 4.8.1 中有以下测试:

g++ -std=c++11 testclass.cpp -o testclass.exe

template<typename T>
class XRef
{
    private :
        int inum ;
        T * ptr ;
        bool owner ;
    public :
        XRef(int i,T *ptrx):inum{i},ptr{ptrx},owner{true}
        {cout << "natural" << endl ;}

        XRef(XRef& x):inum{x.inum},ptr{x.ptr},owner{false}
        {cout << "copy" << endl ;}

        XRef& operator=(XRef& x)
        {
            inum = x.inum ;
            ptr = x.ptr ;
            owner = false ;
            cout << "assign" << endl ;
            return *this ;
        }

        XRef(XRef&& x):inum{x.inum},ptr{move(x.ptr)},owner{true}
        {cout << "move" << endl ;}

        ~XRef()
        {
            if(owner)
                delete ptr ;
        }
} ;

int main()
{
    char *ptr1 ;
    char *ptr2 ;
    ptr1 = (char *) malloc(100) ;
    ptr2 = (char *) malloc(100) ;

    XRef<char> x1 = XRef<char>(1,ptr1) ;
    cout <<"==============" << endl ;
    XRef<char> x2 = x1 ;
    cout <<"==============" << endl ;
    XRef<char> x3(x2) ;
    cout <<"==============" << endl ;
    XRef<char> x4(XRef<char>(123,ptr2)) ;
    cout <<"==============" << endl ;
    XRef<char> x5(move(XRef<char>(123,ptr2))) ;
    cout <<"==============" << endl ;
    XRef<char> x6{123,ptr2} ;
}

然后,输出:

natural
==============
copy
==============
copy
==============
natural
==============
natural
move
==============
natural

令我惊讶的是:外部参照 x2 = x1;,我认为这应该调用 XRef& operator=(XRef& x) ,但是这个测试表明它调用了 XRef(XRef& x) ......

我想知道我做的是错的,所以 operator= 不被调用!

编辑 :

XRef<char> x7{123,ptr2} ;
cout <<"==============" << endl ;
x7 = x6 ;
cout <<"==============" << endl ;

显示:

natural
==============
assign
==============

所以 ,

XRef<char> x2 = x1 ;  

XRef<char> x7{123,ptr2} ;
x7 = x6 ;

怎么会这样?

PS。我指的是:copy construtor call extra for reference ...

4

0 回答 0