Reputation: 3921
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
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:
std::unique_ptr<>
std::thread
std::future<>
std::unique_lock<>
boost::asio::ip::tcp::socket
Upvotes: 5