January 2020
Intermediate to advanced
454 pages
11h 25m
English
Move-only classes prevent a class from being copied, which in some cases, can be a performance improvement. Move-only classes also ensure a 1:1 relationship between resources that are created versus the resources that are allocated, as copies cannot exist. Moving a class, however, can result in a class becoming invalid, as in this example:
#include <iostream>class the_answer{ std::unique_ptr<int> m_answer;public: explicit the_answer(int answer) : m_answer{std::make_unique<int>(answer)} { } ~the_answer() { std::cout << "The answer is: " << *m_answer << '\n'; }public: the_answer(the_answer &&other) noexcept = default; the_answer &operator=(the_answer &&other) noexcept = default;};int main(void){ the_answer is_42{42}; the_answer ...