是否有办法编写一个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));
}
这个习语的一些常见模型有:
-
std::unique_ptr<>
-
std::thread
-
std::future<>
-
std::unique_lock<>
-
boost::asio::ip::tcp::socket