我在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
让我感到惊讶的是:XRef x2 = x1; ,我认为这应该叫XRef&amp; operator =(XRef&amp; x),但是这个测试显示了它的调用 XRef(XRef&amp; 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 called extra作为参考......