Hi All:
I am running NC 6.2.1 with QCC/gcc version 2.95.3. I am trying to get
function try blocks on constructors to work on templated classes.
A function try block for a non templated class would look like:
buffer(size_t const count) throw(bad_alloc)
try
: p(new char[count])
{ /constructor body/ }
catch (exception & e)
{
//do something to catch exception
}
This will compile and work correctly under 2.95.3 and throw a
constructor exception (if the “new” fails) which will be caught by the
constructor. The templated version of this snippet is:
template
class Tbuffer
{
public:
Tbuffer(size_t const count) throw(bad_alloc)
try
: p(new T[count])
{ /constructor body/ }
catch (exception & e)
{
//do something
}
The templated code will also compile, but will not catch the thrown
exception. Any idea what may be going on? Is this just a problem with
2.95.3 specification compliance or do I need to set some other flag?
The complete test code, compile command and results are below.
Thanks in advance for the assistance.
Regards,
–Jeff Strickrott
====================
compile with “QCC -D_PTHREADS=1 test.cpp -o btest”
#include
#include
#include
#include
using namespace std;
class buffer
{
public:
buffer(size_t const count) throw(bad_alloc)
try
: p(new char[count])
{
//throw bad_alloc();
cout << “buffer(size_t const count)” << endl;
}
catch (exception & e)
{
cerr << “caught exception " << e.what( ) << " in buffer”
<< endl;
cerr << "Type " << typeid( e ).name( ) << endl;
exit(1);
}
~buffer() throw()
{
delete[] p;
}
private:
char *const p;
};
//==================================================
//
template
class Tbuffer
{
public:
Tbuffer(size_t const count) throw(bad_alloc)
try
: p(new T[count])
{
//throw bad_alloc();
cout << “Tbuffer<” << typeid( T ).name() <<
“>::Tbuffer(size_t const count)”<< endl;
}
catch (exception & e)
{
cerr << “caught exception " << e.what( ) << " in Tbuffer”
<<endl;
cerr << "Type " << typeid( e ).name( ) << endl;
exit(1);
}
~Tbuffer() throw()
{
cout << “~Tbuffer()” << endl;
delete[] p;
}
private:
T *const p;
};
void main()
{
cout << “test.cpp” << endl;
try
{
Tbuffer Tb(-1); //will throw bad_alloc, but it is not caught
by Tbuffer
//Tbuffer Tb(1);
buffer b(11);
//buffer b(-11); //will throw and catch bad_alloc exception
//that is caught by buffer
}
catch(…)
{
cerr << “caught some exception” << endl;
}
}
//results when buffer throws exception
./btest
test.cpp
Tbuffer::Tbuffer(size_t const count)
caught exception bad_alloc in buffer
Type 9bad_alloc
//results when Tbuffer throws exception
./btest
test.cpp
caught some exception