Why is a condition_variable not MoveAssignable

隐身守侯 提交于 2019-12-12 12:46:52

问题


Why is a condition_variable not MoveConstructible (as per http://en.cppreference.com/w/cpp/thread/condition_variable)? That prohibits inclusion in lots of containers (eg. std::unordered_map) that move things around.

This forces people to use a unique_ptr which incurs one extra heap allocation, which things like make_shared were built to solve. Also if one doesn't have a pool allocator this can become quite inefficient.


回答1:


condition_variable is a synchronization construct that multiple threads are (potentially) using simultaneously. (In fact, that's its purpose.) How could you move it safely? E.g., suppose it directly contains a spinlock. Some thread is spinning on a given address in your process address space and you're going to move the object out from under it?

Any kind of user-mode synchronization construct can't be moved. The thing that does the actual synchronization needs a fixed address. You could force the object to do all of its real work on a heap-allocated object that wouldn't be moved - and there you go right to the indirection to the heap that you wanted to avoid. (Kernel-mode synchronization constructs can be moved: you've got a handle to some OS thing. But they're much more expensive to use.)

They can't be copied either - because what would that mean?

It just has to be this way. Your design must account for it, that's all.

(And I don't really understand the second paragraph of your question. make_shared was built to make ref counts less expensive and don't have anything to do with moving stuff around. A pool allocator may or may not improve any particular situation, much less this one, and you won't know unless you measure it.)



来源:https://stackoverflow.com/questions/38232576/why-is-a-condition-variable-not-moveassignable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!