struct F
{
private:
int* data;
public:
F( int n )
{
data = new int;
*data = n;
}
F( int* p )
{
data = p;
}
F& operator=( const F& f )
{
*data = *(f.get_data());
return *this;
}
F& operator=( F&& f )
{
delete data;
data = f.data;
f.data = nullptr;
return *this;
}
F& operator=( int n ) { *data = n; return *this; }
F operator()()
{
F cpy_f( data );
return std::move( cpy_f );
}
int* get_data() const { return data; }
};
int main()
{
F f( 12 );
F g( 14 );
f() = g();
cout << *(f.get_data()) << endl;
}
In this example, f()
and g()
respectively return a temporary object, so f()=g()
results in an expression of temporary object equal to temporary object. I would have expected that the answer is 14 if the value is correctly copied. However, it is NOT calling the copy assignment, BUT calling the move assignment! As a result, the answer is not 14.
This makes me really confused. Although the returning objects from f()
and g()
are temporary, they are sharing some information with some other objects. It implies the temporary objects might be doing some works shortly for the shared information. So I am supposed that semantically calling copy assignment would be the correct behaviors.
ps. My compiler is g++4.7 20110430