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& 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。私が参照した:参考のためにextraと呼ばれるコピーコンストラクタ ...