简体   繁体   中英

Why inserting at beginning of a vector is valid but unspecified?

After watching Sean Parent's 2016 Keynote: Better Code from BoostCon I am a bit confused about a piece of code that he mentions as

Valid but unspecified

std::vector<int> x = { 1, 2, 3 };
try{
  x.insert(x.begin(), 0);
} catch (...) {
  std::cout << x.size() << std::endl;
}

Why exactly would that be unspecified?

From http://en.cppreference.com/w/cpp/container/vector/insert we read:

 iterator insert( const_iterator pos, const T& value ); (1) iterator insert( const_iterator pos, T&& value ); (2) 

1-2) inserts value before pos

Why inserting at beginning of a vector is valid but unspecified?

It is not.

And it is not what the linked presentation says. What the presentation attempts to convey, is that if inserting a value at the beginning of the vector (to be more accurate: any other position other than end) results in a throw, then the vector will be left in an unspecified but valid state - as opposed to being rolled back to the state that the vector was originally, before attempting the failed operation.

Why exactly would that be unspecified?

Because the standard does not require that std::vector must offer strong exception safety for such operation.


† It is not required in general, but it actually might require it in this case: As bogdan points out in a comment, vector does in fact offer strong exception guarantee, unless the source of the exception is copy constructor or assignment operator ... (other cases) ... and in the case where element type is int , the exception can't be from such source.

So, the example given in the presentation should therefore use some type T whose copy/move constructor or assignment might throw.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM