I have the following code:
class ClassA
{
public:
ClassA(std::string str);
std::string GetSomething();
};
int main()
{
std::string s = "";
try
{
ClassA a = ClassA(s);
}
catch(...)
{
//Do something
exit(1);
}
std::string result = a.GetSomething();
//Some large amount of code using 'a' out there.
}
I would like the last line could access the a
variable. How could I achieve that, given ClassA doesn't have default constructor ClassA()
and I would not like to use pointers? Is the only way to add a default constructor to ClassA
?
You can't or shouldn't. Instead you could just use it within the try
block, something like:
try
{
ClassA a = ClassA(s);
std::string result = a.GetSomething();
}
catch(...)
{
//Do something
exit(1);
}
The reason is that since a
goes out of scope after the try
block referring to the object after that is undefined behavior (if you have a pointer to where it were).
If you're concerned with a.GetSomething
or the assignment throw
s you could put a try-catch
around that:
try
{
ClassA a = ClassA(s);
try {
std::string result = a.GetSomething();
}
catch(...) {
// handle exceptions not from the constructor
}
}
catch(...)
{
//Do something only for exception from the constructor
exit(1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With