This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

c++ warning idea


Recently, I was fixing somebody's c++ code which had a nasty and very hard
to spot bug which a compiler warning probably would have caught.

Consider a class who returns a temporary:

 ..
 Foo GiveAFoo();
 ..

and later, something like this happens:

 const Foo& rfoo = GiveAFoo();

What happens is a temporary Foo object is returned, a reference to it
stored, and the temporary object destructed, ending up with the equivalent
of an uninitialized pointer.  This problem is even harder to spot in my real
world case, where the author of the code implemented his own container
template classes.  The [] operator overload of a list looked something like
this:

 T operator( int i )[] const { .. }
 T& operator( int i ) [] { .. }

(To solve the problem, use
 const T& operator( int i )[] const
instead; it can be faster in some cases for non-simple types).

What happened in this case was a list of lists passed to a function via
const reference, and:
 const item& ritem = list[i].sublist[j];

Talk about an evil problem to post-mortem debug :).

I think a compiler warning would have been extremely helpful in this case.
It is, in fact, pointless to initialize a reference to a temporary, but
there are less than obvious ways where this can be accidentally done.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]