1

For the following code snippet (using C++14 standard), can we declare setDataVectoras noexcept?

class Data {
public:
  using Type = ...; // A class with a default move assignment operator. Or even just uint32_t

  void setDataVector(std::vector<Type> &&input) // Can be declared as noexcept?
  {
    data = std::move(input);
  }

private:
  std::vector<Type> data;
};

In cppreference, it is mentioned that until C++17, the move assignment operator for std::vector is not noexcept.

vector& operator=( vector&& other );

Can it really throw even for trivial datatypes like integer?

What is confusing me is that move operations should be exception-safe but std::vector and std::string for example don't have a noexcept move assignment operators.

So, What am I missing here?

DarkLight
  • 141
  • 1
  • 9
  • 1
    Plain `std::vector` using the standard `std::allocator` will not throw; it just reassigns internal pointers. A vector that uses a custom allocator may, depending on properties of that allocator, be forced to allocate memory and move elements one by one. Memory allocation may then fail. Note that, in C++17, the method is conditionally `noexcept`: `noexcept(std::allocator_traits::propagate_on_container_move_assignment::value || std::allocator_traits::is_always_equal::value)` – Igor Tandetnik Sep 19 '22 at 14:52
  • @IgorTandetnik, so until C++17, the move assignment operator of `std::vector` is `noexcept` if `T`'s move assignment operator is also `noexcept` and `std::allocator` is used, correct? – DarkLight Sep 19 '22 at 16:09
  • If `std::allocator` is used, then properties of `T` don't matter as `T`'s move assignment is not invoked. Why cppreference claims that it's only `noexcept` starting from C++17, I'm not sure. The standard itself doesn't spell out the `noexcept` clause, but only describes in prose what operations are performed, and which of them may throw. The prose seems very similar in C++11 and C++17 (but I admit I didn't go over it very carefully; there may be small distinctions that perhaps have important effects). – Igor Tandetnik Sep 19 '22 at 16:21

0 Answers0