Why aren't container move assignment operators noexcept?

后端 未结 3 1740
借酒劲吻你
借酒劲吻你 2020-12-08 09:32

I noticed that std::string\'s (really std::basic_string\'s) move assignment operator is noexcept. That makes sense to me. But then I

3条回答
  •  时光说笑
    2020-12-08 10:20

    I think the reasoning for this goes like this.

    basic_string only works with non-array POD types. As such, their destructors must be trivial. This means that if you do a swap for move-assignment, it doesn't matter as much to you that the original contents of the moved-to string haven't been destroyed yet.

    Whereas containers (basic_string is not technically a container by the C++ spec) can contain arbitrary types. Types with destructors, or types that contain objects with destructors. This means that it is more important to the user to maintain control over exactly when an object is destroyed. It specifically states that:

    All existing elements of a [the moved-to object] are either move assigned to or destroyed.

    So the difference does make sense. You can't make move-assignment noexcept once you start deallocating memory (through the allocator) because that can fail via exception. Thus, once you start requiring that memory is deallocated on move-assign, you give up being able to enforce noexcept.

提交回复
热议问题