有这么一堂课
class A
{
public:
A(): _size(0), _value(nullptr)
{
std::cout << "A() "<< this << std::endl;
}
A(const int size) : _size( size ), _value( new char[size] )
{
std::cout << "A( const int ) " << this << std::endl;
for (int i = 0; i < _size; ++i)
_value[i] = 'a' + i;
}
~A()
{
std::cout << "~A() " << this << std::endl;
if (_value)
delete[] _value;
}
A( A&& a ):_size(0), _value(nullptr)
{
std::cout << "A( A&& ) "<< this << std::endl;
std::swap( _size, a._size );
std::swap( _value, a._value );
}
A& operator=( A&& a )
{
std::cout << "operator=( A&& ) "<< this << std::endl;
std::swap( _size, a._size );
std::swap( _value, a._value );
return *this;
}
A( const A& a)
{
std::cout << "A( A& ) "<< this << std::endl;
_size = a._size;
_value = new char[_size];
memcpy( _value, a._value, sizeof( char ) * _size );
}
A& operator=( const A& a)
{
std::cout << "operator=( const A& ) " << this << std::endl;
_size = a._size;
if (_value)
delete _value;
_value = new char[_size];
memcpy( _value, a._value, sizeof( char ) * _size );
return *this;
}
private:
int _size;
char* _value;
};
还有几个功能
A f1(int size)
{
return A(size);
}
A foo( A&& a )
{
return A( a );
}
执行此代码时:
int main()
{
A a2 = foo( f1( 5 ) );
return 0;
}
输出如下:
A( const int ) 0050F6E4
A( A& ) 0050F7B4
~A() 0050F6E4
~A() 0050F7B4
也就是说,不调用移动构造函数。问题是为什么以及如何让它被调用?
我会这样做:
因为参数
a
,尽管被声明为A&&
,是函数内部的左值 - 它有一个地址。和move
他一样rvalue
。“我想是的”(c)维尼