Boost logo

Boost Users :

From: boost_www (boost_www_at_[hidden])
Date: 2008-07-16 21:47:35


hello Nat,

Thanks you very much for your explanation!

for 1), I never heard of that idiom. In fact, after playing with C++
for more thant 10 years, I am still keeping finding interesting corners
of the language. :)

What I get from your information is that, the do/while clause is
a MUST-HAVE and is obviously intentional.

for 2), it seems that 'this->' is a question of coding style and generally
we could omit it.

I really appreciate your help! and I believe the moderator of the list
will not yell to us for such topic. :-)

B/Rgds
Max

> 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 mailing list
Boost-users_at_[hidden]


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