constructor throw problem

M

mihai

hi all,

I have a constructor witch at a given time it throws an exception,
and i have an static object of that class,
witch is initialized into the cpp file

the problem is that when the exception is raised the
the application crashes ...

have any idea how to bypass this problem ...

have a nice day,
mihai
 
M

Mehturt

mihai said:
hi all,

I have a constructor witch at a given time it throws an exception,
and i have an static object of that class,
witch is initialized into the cpp file

the problem is that when the exception is raised the
the application crashes ...

have any idea how to bypass this problem ...

have a nice day,
mihai

Can you post an example demonstrating your problem?
 
M

mihai

the code is someting like this ...

class A
{
public:
A()
{
if bad thing happens
throw exception;
}
....
};

class B
{
public:
static const A a;
};

// in B.cpp
const A B::a;

here is the problem ... :(
if A() throws the exception ... the application will creash...
 
D

dj

mihai said:
the code is someting like this ...

class A
{
public:
A()
{
if bad thing happens
throw exception;
}
...
};

class B
{
public:
static const A a;
};

// in B.cpp
const A B::a;

here is the problem ... :(
if A() throws the exception ... the application will creash...

Of course it will crash, since there is no way you can catch the
exception in global scope.
 
C

Carlos Martinez

Search for "Lazy initialization"

Basically is to defer the initialization of your object until you need it.
In your case, I'd use a pointer instead of your atribute

static A* a;

And initialize it with a NULL pointer.

You must give access to a through a getter method, returning a const
reference to a, instead of the pointer you have.

Protect your attribute inside the private section but let the getter in
the public section.

The code will be something like this:
class B {
static const A* a;
public:
static const A& getA() {
if(!a)
a=new A();
return *a;
}
};

// in B.cpp
const A* B::a=NULL;
 
B

Bo Persson

mihai said:
i understand this,

i am looking for a workaround ...

:)

have a nice day ...

As you have probably already understood, there is just two ways to
solve this:

1. don't use a global or static variable
2. don't throw exceptions from the constructor


Your choice! :)


Bo Persson
 

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

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top