Re: Is there any standard/guarantees for exception safety in STL operations?
Kenneth 'Bessarion' Boyd wrote:
On Jul 26, 12:45 pm, Mathias Gaunard <loufo...@gmail.com> wrote:
It is fairly trivial to write a wrapper of std::vector<T>::insert
for example that provides strong exception safety, so I don't see
what you mean by "there is NO WAY" to do it.
Technique is simple: build another temporary vector, then if all
went well swap (which is nothrow). That technique can be virtually
applied in all cases you'd want to make a primitive strongly
exception-safe.
At least for C++0X, std::vector<T>::insert is the only insert member
function that requires fixing. All of the others are required to at
least satisfy the strong exception guarantee
anyway([container.requirements.general]/11, plus tracing all four
listed exemptions to that). However, per [vector.modifiers]/1
simply doing the insert on the copy and then swapping is not
required to make a uniformly strongly exception-safe wrapper for
std::vector<T>::insert : we have unspecified behavior for an
exception- throwing move constructor of a type that is not
copy-constructible.
Is the intent there that the strong exception guarantee on such a
move constructor will prevent the unspecified behavior?
It is a limitation on what you can put into a vector. If the move
constructor throws during a multi element move, we might have lost
some originals and are not assured that they can be restored (beacuse
a move back might throw as well). To avoid that, the implementation
will instead copy Ts internally, and destroy the originals only after
the operation is complete.
However, if the T doesn't even have a copy constructor we are screwed.
That's undefined behavior. You avoid this by just not putting that
kind of Ts into a vector, or at least not in a way so that they have
to be relocated (using reserve might help).
Bo Persson
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]