|
Boost Users : |
From: Nat Goodspeed (nat_at_[hidden])
Date: 2008-07-16 11:40:43
boost_www wrote:
> 1) I found code fragment like this, esp. in macro definitions:
>
> do { \
> \
> // ... \
> } while(0)
>
> Why is the do/while clause needed here?
That's a macro idiom that dates back to classic C. It packages a
compound statement { stmt1; stmt2; } as if it were a single statement.
If you write
#define YOURMACRO(arg) { stmt1; stmt2; }
and a subsequent coder writes this:
if (some_condition)
YOURMACRO(1);
else
std::cout << "Whoops, error.\n";
he or she will get a nasty surprise. It works to drop the semicolon
after YOURMACRO(1), but that imposes a new requirement: some macros must
be followed by semicolons, others must NOT be followed by semicolons,
and the coder must know something about the macro's implementation to
use it correctly.
If you write
#define YOURMACRO(arg) do { stmt1; stmt2; } while (0)
then it's appropriate (required) to write a semicolon after the macro
invocation, and subsequent coders can do that consistently without
needing to know which kind of macro this is.
> 2) I found large amount of code like this in a class implementation:
>
> AClass::func()
> {
> this->func1();
> }
>
> Why is 'this->' needed?
There are a few different reasons.
1. Some people write that as a stylistic preference, since it clarifies
that you're referencing a data member rather than a local variable.
2. In some IDEs, when you write "this->", the IDE pops up a list of
members from which to choose.
3. In some arcane scenarios such as a template subclass derived from a
template base class, the language sometimes requires
this->baseClassMember (though I believe MSVC still permits a plain
baseClassMember reference as an extension).
But if you ask any more such questions on this list, the moderator might
yell at both of us. ;-)
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net