我有一個數組類,我抓住一個網站,給出了一個移動構造函數的例子。然而,如何在示例程序中實現這個移動構造函數呢?我覺得我理解函數定義,但我不知道如何在程序中使用它。實現一個數組類的移動構造函數(右值引用)
class ArrayWrapper
{
public:
// default constructor produces a moderately sized array
ArrayWrapper()
: _p_vals(new int[ 64 ])
, _size(64)
{}
ArrayWrapper (int n)
: _p_vals(new int[ n ])
, _size(n)
{}
// move constructor, how does this come in handy?
ArrayWrapper (ArrayWrapper&& other)
: _p_vals(other._p_vals )
, _size(other._size)
{
other._p_vals = NULL;
}
// copy constructor
ArrayWrapper (const ArrayWrapper& other)
: _p_vals(new int[ other._size ])
, _size(other._size)
{
for (int i = 0; i < _size; ++i)
{
_p_vals[ i ] = other._p_vals[ i ];
}
}
~ArrayWrapper()
{
delete [] _p_vals;
}
private:
int *_p_vals;
int _size;
};
[什麼是移動語義](http://stackoverflow.com/questions/3106110/what-are-move-semantics) – 0x499602D2 2013-05-13 23:48:45