STL sort throw exception?

G

George2

Hello everyone,


In Bjarne's book, it is mentioned that sort of STL may throw
exception, like sorting elements in a vector.

In what situation will sort throw exception? I can not find a case.


thanks in advance,
George
 
A

AnonMail2005

Hello everyone,

In Bjarne's book, it is mentioned that sort of STL may throw
exception, like sorting elements in a vector.

In what situation will sort throw exception? I can not find a case.

thanks in advance,
George

When the sort moves elements around, the copy constructor or the
assignment operator of the objects being sorted may throw. It
escapes me at the moment which method (copy construction or
assignemt) is used in the sort algorithms.

HTH
 
V

Victor Bazarov

George2 said:
In Bjarne's book, it is mentioned that sort of STL may throw
exception, like sorting elements in a vector.

In what situation will sort throw exception? I can not find a case.

Since no limitation is put on the comparison functor (whether the
default 'std::less' or the user-defined one), so it may throw, and
the exception will be propagated, i.e. 'sort' does not attempt to
catch it.

V
 
V

Victor Bazarov

When the sort moves elements around, the copy constructor or the
assignment operator of the objects being sorted may throw. It
escapes me at the moment which method (copy construction or
assignemt) is used in the sort algorithms.

Shouldn't it actually be 'swap'?

V
 
H

Howard Hinnant

"Victor Bazarov said:
Shouldn't it actually be 'swap'?

The C++03 sort doesn't specify. In practice implementations use all of:

swap
copy construction
copy assignment.

The C++0X working paper currently has for sort:
Requires: The type of *first shall satisfy the Swappable
requirements (37), the MoveConstructible requirements
(Table 33), and the the MoveAssignable requirements (Table 35).

This will allow sorting sequences of "move only" types such as fstream
and unique_ptr.

With respect to the original question: sort can still throw in C++0X by
similar means: swap, move construct, move assign, comparison. If it
does, the basic guarantee is in effect: no memory leaks or corruption.

-Howard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,787
Messages
2,569,629
Members
45,329
Latest member
InezZ76898

Latest Threads

Top