Does std::vector::emplace() really offer the strong exception guarantee in the face of a throwing move constructor/assignment operator?

后端 未结 1 1315
小蘑菇
小蘑菇 2021-01-05 05:12

According to cppreference.com, std::vector::emplace() offers the strong exception guarantee unconditionally:

If an exception is thrown (e.g. by the co

相关标签:
1条回答
  • 2021-01-05 06:00

    According to the C++14 standard the strong exception guarantee only holds if the type you insert itself has a strong exception guarantee.

    Here:

    23.3.6.5 vector modifiers [ vector.modifiers ]

    iterator insert(const_iterator position, const T& x);
    iterator insert(const_iterator position, T&& x);
    iterator insert(const_iterator position, size_type n, const T& x);
    template <class InputIterator>
    iterator insert(const_iterator position, InputIterator first, InputIterator last);
    iterator insert(const_iterator position, initializer_list<T>);
    template <class... Args> void emplace_back(Args&&... args);
    template <class... Args> iterator emplace(const_iterator position, Args&&... args);
    void push_back(const T& x);
    void push_back(T&& x);
    

    1 Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens, all the iterators and references before the insertion point remain valid. If an exception is thrown other than by the copy constructor, move constructor, assignment operator, or move assignment operator of T or by any InputIterator operation there are no effects. If an exception is thrown while inserting a single element at the end and T is CopyInsertable or is_nothrow_move_constructible::value is true, there are no effects. Otherwise, if an exception is thrown by the move constructor of a non-CopyInsertable T, the effects are unspecified.

    So it looks like cppreference.com is wrong.

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