Skip to main content
gamedev.net
🔒 Locked

a question about C++ Macro

Started by badkeeper3410 Sep 1, 2005 at 10:09 AM 4 replies 1.4k views
Original Post
badkeeper3410
badkeeper3410
Hello all. Today I found a weird use of c++ macro and I really not know what it mean. maybe somebody can help me;:) eg: #define new (m_setOwner (__FILE__,__LINE__,__FUNCTION__),false) ? 0 : new the function m_setOwner () just return void; what confused me most is the "false". what's that mean?
Fruny
Fruny
First, #defining new is an abomination.
Second, macros are neither a C nor a C++ features, they're handled by the preprocessor.

Now, the comma (outside of a parameter list) is the sequencing operator, meaning that a, b will first evaluate a, then evaluate b. The value of the expression a,b will be b.

So m_setOwner (__FILE__,__LINE__,__FUNCTION__),false will first call m_setOwner then discard its return value and evaluate to false, which means it will skip to the second half of the conditional operator, do and evaluate to a new whatever_followed_the_macro_in_the_first_place.

The reason for such a convoluted operation is not have the code break if you use the macroed new in a context where the comma would be interpreted as a parameter separator. You can't just slap a pair of parentheses around the macro, since new needs elements which follow the macro rather than being provided with it. So instead you hack the conditional operator ?: which should always be interpreted in the same way: evaluate the condition then whichever branch got selected.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
badkeeper3410
badkeeper3410
thanks for the help. It's really a useful trick
FlowingOoze
FlowingOoze
As fruny said, defining new as a macro isn't that smart.
It's much better to use implementation specific functions in the overloaded new operator to get the return address of the function, then use other tools to figure out what the source file and line was based on the address.
In GCC you can use __builtin_return_address (unsigned int level) to get the address and the command line tool addr2line to find the soure file, line number and function.
daerid
daerid
Is there a Win32 equivalent?

Finding the source file and line of a call to new is all but impossible without the trick show above.
daerid@gmail.com
FlowingOoze
FlowingOoze
Quote:
Original post by daerid
Is there a Win32 equivalent?

If you're using GCC then the above works even in Win32. :)
I'm afraid I don't know about other compilers and toolsets, but I'm sure there have to be equivalent functions and commands. Check your documentation.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.