Andrei Bozantan
Andrei Bozantan

Reputation: 3921

C++ class with compiler enforced unique ownership semantics for objects

Is there any way to write a C++ class such that the compiler will enforce unique ownership semantics on the objects?

Upvotes: 1

Views: 117

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69864

Yes. Simply disable copy/assignment and enable move.

struct unique_thing
{
  unique_thing() = default;  // you can create me
  unique_thing(unique_thing&&) = default; // and move me
  unique_thing(unique_thing const&) = delete; // but not copy me

  unique_thing& operator=(unique_thing&&) = default; // you may move-assign me
  unique_thing& operator=(unique_thing const&) = delete; // but not copy-assign me
};

Which we can boil down to a handy base class (note: virtual destructors not necessary because no-one will ever own an object through this class):

#include <utility>
#include <type_traits>
#include <cassert>

struct only_moveable
{
  protected:
  constexpr only_moveable() noexcept = default;
  constexpr only_moveable(only_moveable&&) noexcept = default;
  constexpr only_moveable& operator=(only_moveable&&) noexcept {};
};

struct MyClass : only_moveable
{
};


int main()
{
  // creatable
  MyClass a;

  // move-constructible
  MyClass b = std::move(a);

  // move-assignable
  a = std::move(b);

  // not copy-constructible
  assert((not std::is_copy_constructible<MyClass>::value));

  // not copy-assignable
  assert((not std::is_copy_assignable<MyClass>::value));  
}

some common models of this idiom are:

  1. std::unique_ptr<>
  2. std::thread
  3. std::future<>
  4. std::unique_lock<>
  5. boost::asio::ip::tcp::socket

Upvotes: 5

Related Questions