@hamsterman
if you dynamic_cast a NULL pointer or a pointer to a memory that was freed (deleted) you get a segmentation fault, that's why I check the pointer with the first if-statement.
@Andy
poor style to assign within an if condition. |
is it? Because I think it's quite useful when you want a temporary variable just for the scope of the if-statement.
The macro is 100% perfectly working (I'm using the GNU GCC compiler version 4.5.2) I'm not sure if that matters.
I don't usually declare variables within an if statement but since it is possible and this is a macro I thought it would be convenient enough to do so. There's no problem in that
1 2 3 4 5
|
if( int A = f() ) // A gets created, the return value of f() is assigned to A, the if-statement checks whether the new value of A != 0
{
// A is still in scope so you can do things like
cout << A << endl; // no problem with this code
} // This is where A goes out of scope
|
The code you provided would be perfect for my case but it's not actually the one my macro evaluates to. There's a slight difference (which brings the problem)
My macro evaluates to:
1 2 3 4 5 6
|
if(object_ptr) // if the pointer isn't NULL
if(Interface * self = dynamic_cast<Interface *>(object_ptr))
// if the dynamic_cast didn't return NULL (this means everything is OK with the cast)
{
// this is the code block following the macro
}
|
There's no way I can close the brackets of the first if-statement because the last curly bracket (in your code) in no way can be part of the same macro. I'll have to close it manually which is something I'm trying to avoid.
I'm trying to combine the two if-statements into one so when I use
else
right after the macro it would correctly lead to the code where the whole macro did not execute.
Consider the following code
1 2 3 4 5 6 7 8 9
|
using(Interface, obj_ptr)
{
// some code if the cast was successful
}
else
{
cout << "There was a problem with the pointer" << endl;
}
|
The control wouldn't reach the
cout
if the pointer equals NULL because the
else
refers to the second
if
and not the first one. I can make the
else
to refer to the first if by either enclosing the inner if in curly brackets or appending
else;
at the end of the block following the macro. But both of those solutions involve writing additional code outside the macro just to make it work.