dick wrote:
Alf P. Steinbach wrote:
* dick:
in the "try{throw}catc h" structure, how the C++ code return the "type"
thrown by a function?
Short answer: Magic.
Almost-short answer: the dynamic type of the object throw by 'throw' is
known statically, and is the same as the static type because objects are
thrown by value, and the static type of object caught by 'catch' is
known statically, and is the only thing that matters for whether a
'catch' clause will catch. The linker has access to all this
information. And so it can arrange the necessary tables or global type
identifiers or whatever the implementation is based on (there are two
main ways to do it, but an infinite number of possible ways to do it).
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
is there any memory leak when a function throw an object?
Oh yes there can be. *If* you allocate with new, the compiler is no
longer responsible for that allocation. That does not change when an
exception is thrown.
Obviously, any local objects are automatically destroyed. The same
holds with smart pointers.
You can safely protect yourself:
a) by not using new/delete
b) using smart pointers
c) by having the catch block check for and deallocate any newed
allocations. That - you need to do carefully.
Take for example the code below and lets artificially throw a
bad_allocation exception before delete invokes A's d~tor.
#include <iostream>
#include <stdexcept>
class A
{
};
int main()
{
// pointer must not be in try block
A* p_a = 0; // nullified
try
{
A a; // local
p_a = new A;
std::cout << "p_a = " << p_a << std::endl;
// do stuff and throw for a test
throw std::bad_alloc( ); // or std::runtime_er ror
delete p_a;
std::cout << "end of try block\n";
}
catch( const std::exception& e)
{
std::cerr << "error: ";
std::cerr << e.what() << std::endl;
std::cerr << "p_a = " << p_a << std::endl;
if(p_a)
{
delete p_a;
std::cerr << "*** p_a deleted ***" << std::endl;
}
}
}
/*
p_a = 0x503010
<- "end of try block" was never reached
error: St::bad_alloc <- in catch block
p_a = 0x503010
*** p_a deleted ***
*/