C++:关于使用 Stroustrup 示例移动构造函数/赋值的问题

C++: question about move constructor/assignment using Stroustrup example

本文关键字:构造函数 赋值 问题 移动 于使用 Stroustrup C++      更新时间:2023-10-16

我理解右值如何调用移动构造函数和移动赋值运算符,但是我很困惑为什么下面 Stroustrup 示例中用于移动赋值的相同代码不用于移动构造函数。 本文摘自第 4 版第 379 页修订的勘误表C++。

由于类中的所有对象都在移动构造函数中复制,为什么移动构造函数不能像移动赋值运算符那样简单地交换对象的指针?

也许我错过了一些东西,感谢您的指导!

template<typename T, typename A = allocator<T>>
struct vector_base {                    // memory structure for vector
A alloc;        // allocator
T* elem;        // start of allocation
T* space;       // end of element sequence, start of space allocated for possible expansion
T* last;        // end of allocated space
vector_base(const A& a, typename A::size_type n, typename A::size_type m =0)
: alloc{a}, elem{alloc.allocate(n+m)}, space{elem+n}, last{elem+n+m} { }
~vector_base() { alloc.deallocate(elem,last-elem); }
vector_base(const vector_base&) = delete;           // no copy operations
vector_base& operator=(const vector_base&) = delete;
vector_base(vector_base&&);                     // move operations
vector_base& operator=(vector_base&&);
};
template<typename T, typename A>
vector_base<T,A>::vector_base(vector_base&& a)
: alloc{a.alloc},
elem{a.elem},
space{a.space},
last{a.last}    
{
a.elem = a.space = a.last = nullptr;    // no longer owns any memory
}
template<typename T, typename A>
vector_base<T,A>& vector_base<T,A>::operator=(vector_base&& a)
{
swap(*this,a);
return *this;
}

移动构造函数无法执行交换,因为它的成员未初始化,析构函数将无法在传递的右值上正常工作。因此,移动构造函数必须逐个复制每个元素,并将右值的成员设置为 null,以便右值析构函数将起作用。移动赋值可以与右值进行交换,因为当调用右值析构函数时,数据将是有效的(并且是来自潜在右值的常规构造函数的数据(。