How it works...

A move-only class is a class that can be moved but cannot be copied. To explore this type of class, let's wrap std::unique_ptr, which itself is a move-only class, in the following example:

class the_answer{    std::unique_ptr<int> m_answer;public:    explicit the_answer(int answer) :        m_answer{std::make_unique<int>(answer)}    { }    ~the_answer()    {        if (m_answer) {            std::cout << "The answer is: " << *m_answer << '\n';        }    }public:    the_answer(the_answer &&other) noexcept    {        *this = std::move(other);    }    the_answer &operator=(the_answer &&other) noexcept    {        m_answer = std::move(other.m_answer);        return *this;    }};

The preceding class stores std::unique_ptr as a member variable and, on construction, instantiates the memory variable with an integer ...

Get Advanced C++ Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.