具有编译器强制对象唯一所有权语义的c++类



是否有办法编写一个c++类,使编译器在对象上强制执行唯一的所有权语义?

是。只需禁用复制/分配并启用移动。

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
};

我们可以将其归结为一个方便的基类(注意:虚析构函数是不必要的,因为没有人会通过该类拥有对象):

#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));  
}

这个习语的一些常见模型有:

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

最新更新