Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Move assignment operator without custom swap function?

Tags:

c++

swap

I'm reading Stroustrup's book (4th ed) and saw this example:

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

From this answer, I understand that you can't just std::swap(*this, other) in an assignment operator because std::swap is often implemented in terms of the assignment operator itself. Therefore, you first need to provide your own custom swap function.

Is this a mistake, or am I missing something?

like image 804
Martin Avatar asked Mar 31 '26 20:03

Martin


1 Answers

Looks like this is a duplicate of Usage of std::swap() inside move assignment should cause endless recursion (and causes), but it is an example from Stroustrup's book. Seems like Stroustrup does define a custom swap function; I seem to have missed it.

EDIT: I haven't found the swap function. Seems like it's a mistake on the book.

like image 182
Martin Avatar answered Apr 03 '26 17:04

Martin