I have the following test in 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} ;
}
Then , the output :
natural
==============
copy
==============
copy
==============
natural
==============
natural
move
==============
natural
What surprise me is that : XRef x2 = x1 ; , I think this should call XRef& operator=(XRef& x) , but this test showes it call XRef(XRef& x) instead ....
I like to know what i do is wrong , so that operator= is not called !!
Edit :
XRef<char> x7{123,ptr2} ;
cout <<"==============" << endl ;
x7 = x6 ;
cout <<"==============" << endl ;
Showes :
natural
==============
assign
==============
So ,
XRef<char> x2 = x1 ;
is different with
XRef<char> x7{123,ptr2} ;
x7 = x6 ;
How come this happened ?
PS. I refered to : copy construtor called extra for reference ...