繁体   English   中英

C++ - 在没有自定义交换 function 的情况下移动赋值运算符?

[英]C++ - Move assignment operator without custom swap function?

我正在阅读 Stroustrup 的书(第 4 版)并看到了这个例子:

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;
}

这个答案中,我了解到您不能只在赋值运算符中使用std::swap(*this, other) ,因为std::swap通常是根据赋值运算符本身来实现的。 因此,您首先需要提供自己的自定义swap function。

这是一个错误,还是我错过了什么?

看起来这是在移动赋值中使用 std::swap() 的副本应该导致无限递归(和原因),但它是 Stroustrup 书中的一个例子 似乎 Stroustrup 确实定义了一个自定义交换 function; 我好像错过了。

编辑:我还没有找到交换 function。 好像是书上写错了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM