Are move constructors required to be noexcept?

后端 未结 2 1512
夕颜
夕颜 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:38

    Are move constructors in general allowed to throw? Yes. Should they? No.

    In general, nothing you do within them should be anything that could throw. You shouldn't be allocating memory, calling other code, or anything like that. The only reason to write a move constructor is to abscond with someone else's memory pointers and object references. You should be copying a few basic types and nulling out the values in the other object. Those things shouldn't throw.

    So while it is allowed, it's not a good idea. If you're doing it, rethink what you're doing in your move operations.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题