带有编译器的 C++ 类为对象强制实施唯一的所有权语义

And*_*tan 1 c++

有没有办法编写一个 C++ 类,以便编译器对对象强制执行唯一的所有权语义?

Ric*_*ges 5

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

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
};
Run Code Online (Sandbox Code Playgroud)

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

#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));  
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 在提到 Boost.Asio 之前,我会添加 `std::thread`、`std::unique_lock` 和更多的 `std::` 和常见的 `boost::` 示例。 (2认同)
  • 那个斜坡是光荣的 (2认同)