gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:42:45 26 4
gpt4 key购买 nike

有没有什么方法可以编写 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

关于具有编译器的 C++ 类强制对象的唯一所有权语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39043047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com