Reputation: 2096
If memory allocation fails while moving a object into a std::vector, and bad_alloc is thrown, does std::vector guarantee that the moved from object is unaltered/still valid ?
For example:
std::string str = "Hello, World!";
std::vector<std::string> vec;
vec.emplace_back(std::move(str));
/* Is str still valid and unaltered if the previous line throws? */
Upvotes: 1
Views: 288
Reputation: 180935
This is covered in [container.requirements.general]/11.2
if an exception is thrown by a
push_back()
,push_front()
,emplace_back()
, oremplace_front()
function, that function has no effects.
So, you will not have a moved from object in the event of an exception.
This only covers if the vector throws. We need to look at [vector.modifiers]/1 to see what happens if the move constructor itself throws:
If an exception is thrown while inserting a single element at the end and
T
is Cpp17CopyInsertable oris_nothrow_move_constructible_v<T>
istrue
, there are no effects. Otherwise, if an exception is thrown by the move constructor of a non-Cpp17CopyInsertableT
, the effects are unspecified.
emphasis mine
And in that case the behavior is unspecified.
In your case std::string
has a noexcpet
move constructor so you will have a valid object if an exception throws.
Upvotes: 7