Skip to Content
Advanced C++ Programming Cookbook
book

Advanced C++ Programming Cookbook

by Dr. Rian Quinn
January 2020
Intermediate to advanced
454 pages
11h 25m
English
Packt Publishing
Content preview from Advanced C++ Programming Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern C++ Programming Cookbook

Modern C++ Programming Cookbook

Marius Bancila

Publisher Resources

ISBN: 9781838559915Supplemental Content