On Apr 7, 11:35 pm, Roberto Giaffy <gia...@gmail.com> wrote:
I want to understand if sometime it is possible to be sure
a function / method will never throw an exception;
I think a function / method that only perform assignment / copy
operation on primitive types like int, bool, double etc., then
it is guarantee it will never throw an exception
so it can be qualified with "throw()"
(Note: just at this very beginning, I do not want to ask
if it is a good practice such a qualifying, just suppose
it is already present in some old library)
But I wonder if a class containing basic type (or also
other class containing basic types) can be manipulated
and the function / method can still offering a no-throw guarantee;
an example:
// a class of only basic types
class A {
int i;
double j;
bool k;
public:
A() : i(0), j(0), k(0) {};
A( int I, doule J, bool K ) : i(I), j(J), k(K) {};
};
// a function that call constructor,
// copy constructor, copy operator and
// create a temporary object A
A afunction( int i, double j, bool k) throw()
{
A a( i, j, k);
A b= a;
A c;
c= b;
return( A( i, j ,k) );
}
It will be correct the fun. afunction() will never throw ? or I am
missing
some fundamental point ?
The fundamental point is that in standard C++, exceptions are not
thrown from thin air. Operations on primitives do not throw, where
primitives are things like the integers, characters, pointers.
Operations on simple structs and classes of only primitives
(collectively known as POD types, using this informal definition) do
not throw. The only things which can throw are a "throw" statement,
dynamic_cast on a reference type, standard library functions and
standard language features and functions which are documented as can
throw an exception (most prominently operator new), and any function
which directly or indirectly does any of those things. (I might be
missing some other thing which can throw. It's late, and I can't
recall off the top of my head.) Your code has none of those things
which can throw, so your code does not throw.