为什么std :: mutex既不可复制又不可移动? [英] Why is std::mutex neither copyable nor movable?

查看:133
本文介绍了为什么std :: mutex既不可复制又不可移动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能说出为什么 std :: mutex 既不可复制又不可移动的原因?有人告诉我,它与避免资源浪费有一些关系.为什么 std :: mutex 的副本构造函数应标记为已删除?如果没有,是否有任何潜在的问题?它的copy构造函数明显地标记为已删除,但是我没有看到它的motion构造函数这样的声明.那么为什么 cppreference std :: mutex 不能移动?

Could somebody tell the reasons why std::mutex is neither copyable nor movable? Somebody told me that it has some relationship to avoid resource waste. Why the copy constructor of std::mutex should be marked as deleted? If not, is there any potential problem? Its copy constructor is clearly marked as deleted, but I have not seen such declaration for its movement constructor. So why does cppreference say std::mutex is not movable?

推荐答案

在其他答案上稍作扩展,互斥锁等基本锁是语言设计中提供原子操作的最基本对象, lock unlock 此处.这些可能拥有一个OS实现的句柄( native_handle ),它是硬件实现的对象的句柄,甚至可能跳过中间句柄.

Expanding a bit on the other answers, basic locks such as Mutexes are the most basic objects in the language design providing atomic operations, lock and unlock here. These might own an OS implemented handle (native_handle) that is a handle for a hardware implemented object, and might even skip the intermediate handle.

复制这样的句柄当然是很简单的(您不能复制一件硬件,有时甚至是OS句柄).移动它可能会更糟-移动会使对象处于未指定的状态,但从本质上讲,互斥锁在线程之间共享.如果将其放在一个线程上,则您将不得不以某种方式通知所有其他线程-更可能是您的代码破了.没有任何潜在的好处,这是很多开销(我可以看到).

Copying such a handle of course, is non-trivial (you can't copy a piece of hardware, and sometimes even a OS handle, trivially). Moving it is potentially worse - move leaves the object in an unspecified state, but by its nature, a mutex is shared across threads. If you gut it on one thread, you would somehow have to inform all other threads - more likely you would just have breaking code. This is a lot of overhead for no potential benefit (I can see).

关于为什么未在您的引用中明确删除move构造函数的原因-如果存在(非默认)定义的 destructor ( 12.8,评论9 ),因此无需删除它.

As to why the move constructor is not explicitly deleted in your reference - no default move constructor is created if there is a (non-default) defined destructor (12.8, comment 9), so there is no need to delete it.

这篇关于为什么std :: mutex既不可复制又不可移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆