Date: Mon, 20 May 2024 07:59:41 +0100
On Sun, May 19, 2024 at 11:49 PM Sebastian Wittmeier wrote:
>
> Now exception handling and destruction order should be simple.
Or here's another way of doing it:
If an exception is thrown and propagates outside of the function,
then all destructors are invoked in the regular order -- except for
the destructor of the return object, which is invoked last.
So then whenever we have a function such as:
struct SomeClass {
SomeClass(char const*);
SomeClass(int, double);
void Eat(void);
void Drink(void);
};
SomeClass Func(void) _Retvar
{
SomeClass *p = nullptr;
std::string str = some_global_variable;
if ( cond )
{
p = &_Retvar{ 5, 2.0 };
}
else if ( cond2 )
{
str += "frog";
p = &_Retvar{ str.c_str() };
}
else
{
return SomeClass( "chocolate" );
}
p->Eat();
p->Drink();
return _Retvar;
}
It will behave as though you wrote:
SomeClass Func(void) _Retvar
{
SomeClass *p = nullptr;
try
{
std::string str = some_global_variable;
if ( cond )
{
p = &_Retvar{ 5, 2.0 };
}
else if ( cond2 )
{
str += "frog";
p = &_Retvar{ str.c_str() };
}
else
{
return SomeClass( "chocolate" );
}
p->Eat();
p->Drink();
return _Retvar;
}
catch (...)
{
if ( nullptr != p ) p->~SomeClass();
throw;
}
}
>
> Now exception handling and destruction order should be simple.
Or here's another way of doing it:
If an exception is thrown and propagates outside of the function,
then all destructors are invoked in the regular order -- except for
the destructor of the return object, which is invoked last.
So then whenever we have a function such as:
struct SomeClass {
SomeClass(char const*);
SomeClass(int, double);
void Eat(void);
void Drink(void);
};
SomeClass Func(void) _Retvar
{
SomeClass *p = nullptr;
std::string str = some_global_variable;
if ( cond )
{
p = &_Retvar{ 5, 2.0 };
}
else if ( cond2 )
{
str += "frog";
p = &_Retvar{ str.c_str() };
}
else
{
return SomeClass( "chocolate" );
}
p->Eat();
p->Drink();
return _Retvar;
}
It will behave as though you wrote:
SomeClass Func(void) _Retvar
{
SomeClass *p = nullptr;
try
{
std::string str = some_global_variable;
if ( cond )
{
p = &_Retvar{ 5, 2.0 };
}
else if ( cond2 )
{
str += "frog";
p = &_Retvar{ str.c_str() };
}
else
{
return SomeClass( "chocolate" );
}
p->Eat();
p->Drink();
return _Retvar;
}
catch (...)
{
if ( nullptr != p ) p->~SomeClass();
throw;
}
}
Received on 2024-05-20 06:59:53