Why is there no need to mark the move constructor of a type with a deleted copy constructor as deleted?

♀尐吖头ヾ 提交于 2020-06-23 11:06:48

问题


Consider std::mutex. I understand why std::mutex should not be movable. But its copy constructor is clearly marked as deleted, but I have not seen such a declaration for its move constructor. So why does cppreference say std::mutex is not movable?

As per the documentation(https://en.cppreference.com/w/cpp/language/move_constructor), there are many preconditions that are not fulfilled that prevent the implicit move constructor. But I could not find the reason for this question. I would be grateful to have some help with this question.

I really don't think this one(en.cppreference.com/w/cpp/thread/mutex/~mutex) is the user-defined destructor for std::mutex.


回答1:


There are two reasons why the implicit move constructor is not generated by the compiler:

  • std::mutex might have a user-defined destructor. On some platforms, mutex objects allocate memory, so the destructor has to clean that up, for example by calling pthread_mutex_destroy().
  • The copy constructor is explicitly deleted, which counts as being "user-declared".

So why is the standard written in such a way that the above cases prevent the generation of an implicit move constructor? First think of a class where you don't have any constructor/destructor/copy/move operator defined. Then the whole class just behaves as a collection of member variables. The logical thing to do when constructing/destructing/copying/moving such a collection is just to apply the operation on each item individually. However, as soon as you user-define on of those operations, you are adding new semantics to your class, and basically it is no longer just a collection of member variables. The compiler isn't smart enough from looking at the operations you user-defined how to implicit create all the other operations, so the safe thing to do is to not implicit create them.



来源:https://stackoverflow.com/questions/62370747/why-is-there-no-need-to-mark-the-move-constructor-of-a-type-with-a-deleted-copy

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