Copy and Swap Idiom and Iterators

Viewed 66

I have been writing a doubly linked list with nested iterators. When I was working on copy constructor and operator= overloading, I came across Copy-swap-idiom. But from what I realize, it uses the RULE OF THREE (and a Half, if you want). But iterators don't have a destructor, because the "node" they point to isn't their "property", its doubly lists.

This is a university assignment and I am asked to write a copy constructor and operator no matter what the case, wether it's the same as implicit definition or not.

My question is does copy-swap-idiom always need to have a destuctor? If so in Iterators case, would this work or should I use normal "dirty" assignment? Below is relevant part of my iterator class:

template<class T>
class List<T>::ForwardIterator {
private:
    Node<T> *current;

public:
    ForwardIterator(Node<T> *curr = nullptr) : current(curr) {}
    ForwardIterator(const ForwardIterator& right) : current(right.current) {}
...
...

Above part shows the constructors and private data of iterator. Below part shows it's assignment and swap function.

friend void swap(ForwardIterator& first, ForwardIterator& second) {
    using std::swap;
    swap(first.current, second.current);
}

ForwardIterator& operator=(ForwardIterator right) {
    swap(*this, right);
    return *this;
}

This is my implementation, and I wanted to know is it wise to use here? (My iterator doesn't have a destructor, hence my question).

1 Answers

What you have is correct and will work, but it is not needed.

Since your iterator isn't responsible for the node it is holding a pointer to it is fine to have a do nothing destuctor. Because you have a do nothing destructor you don't need to do anything special for any of the copy/move constructors or copy/move assignment operators. This means you don't need to define any of them and you can follow the rule of zero.

Remember, you only need to implement the rule of 3/rule of 5 when your class is actually responsible for acquiring and releasing a resource. If all you are doing is dealing with POD/RAII types then the compiler defaults will "do the right thing".

Related