Are move constructors required to be noexcept?

后端 未结 2 1533
夕颜
夕颜 2021-01-03 23:24

I\'ve been reading some contradicting articles in regards whether move constructors/assignment is allowed to throw or not.

Therefore I\'d like to ask whether move co

2条回答
  •  滥情空心
    2021-01-03 23:39

    Here's to shed some further light on this.

    It seems that std::vector in particular is picky about whether or not you declare your move constructors with noexcept. If you do, then std::vector will use them. If you don't then std::vector will resort to using your copy constructor instead. At least in some cases. Notably whenever it reshuffles items internally, after an internal array resize.

    You can see the effects in this example, where noexcept is not declared:

    http://coliru.stacked-crooked.com/a/285cd07a9a52da3b

    And in this example, where it is:

    http://coliru.stacked-crooked.com/a/d043774ec4c279ec

    In the first example, std::vector uses the copy constructor already at the second and third insertion with push_back. In the second example, it does the same operation, but with the move constructor instead.

提交回复
热议问题