[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[lmi] Forward declaration preceding friend declaration
From: |
Greg Chicares |
Subject: |
[lmi] Forward declaration preceding friend declaration |
Date: |
Sat, 10 Mar 2007 14:26:27 +0000 |
User-agent: |
Thunderbird 1.5.0.4 (Windows/20060516) |
A friend declaration can be written for a class that has not
yet been declared. Existing code does this:
grep 'friend class .*_*[Tt]est' *.?pp
and so do the examples in C++03 11.4/2 . This is allowed by
7.1.5.3/1 for the form 'friend class-key ::opt identifier ;'.
See also 11.4/9: "For a friend class declaration, if there is no
prior declaration,..."; see 'rtti_lmi.hpp' for an example that
requires a forward declaration because of the part I elided
(and note that g++ would diagnose its absence).
On 20070310T1254Z I removed a forward declaration to conform to
that existing practice. I wouldn't expect anyone else to have
noticed that, and I don't think I've ever seen a guideline about
this in any coding standard. I'm not even sure which way is
better; I mostly want uniformity because that helps me read the
code. But...which way is better?
(1) Always declare a class before befriending it, adding a
forward declaration if its full declaration isn't otherwise
necessary.
(2) Never forward declare a class just to befriend it unless
a really good compiler (g++ or EDG) requires you to.
http://groups.google.com/group/comp.lang.c++.moderated/msg/8e1316ea67b1b842
John Potter, in article <address@hidden>,
suggested (1). I think he was saying, though, that (in 1999)
we couldn't rely on a compiler like g++ to diagnose erroneous
usage, so we needed to inculcate a habit like this in order to
avoid writing incorrect code. These days, however, I haven't
seen EDG require a forward declaration where g++ didn't.
http://groups.google.com/group/comp.lang.c++.moderated/msg/a029055cb7c8e209
Martin Fabian, in article <address@hidden>,
presents this counterpoint:
| >Put the function
| >declaration ahead of the class that makes it a friend.
|
| But think about whether you really want to do that. In some cases the
| friend is just there as a helper, and then you may not want to make
| (pointers/refs) to this class available to the user, nor do you want to
| nest it within its friend.
In this day and age, I tend to think (2) is better. Less is more:
a forward declaration that isn't written doesn't need to be read
or maintained; if deleting a line doesn't change the meaning of
the program or make it less clear, then delete that line. We have
tools (g++, e.g.) that will tell us whenever we need to add a
forward declaration. But no tool will warn us when we fail to
write a redundant forward declaration as (1) would require.
Feel free, of course, to present any different point of view.
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- [lmi] Forward declaration preceding friend declaration,
Greg Chicares <=