[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: a weird compiling error in gcc4.2.2

From: Bernd Strieder
Subject: Re: a weird compiling error in gcc4.2.2
Date: Fri, 22 Aug 2008 12:35:45 +0200
User-agent: KNode/0.10.9


kuangye wrote:

> #include <iostream>
> using namespace std;
> class TSB
> {
> //-----key point 1
> friend TSB fnbase();
> //-----key point 2
> protected:

> //-----key point 3
> TSB(const TSB&other)
> {
> cout<<"TSB(const TSB&other)"<<endl;
> }

> TSB fnbase()
> {
> return TSB();
> }

> TS fn()
> {
> //in gcc 4.2.2, the following statement will cause compiling error.
> /*
> 1.cpp: In function 'TS fn()':
> 1.cpp:12: error: 'TSB::TSB(const TSB&)' is protected
> 1.cpp:52: error: within this context
> */
> //But it works in gcc 3.4.
> //---
> return TS(fnbase());
> //It seems that in gcc4.2.2.  "return TS(fnbase());" will convert to
> the following two statement
> //..
> //TSB ret = fnbase();
> //return TS(ret);

This is to be expected. If a value is returned by value, then the copy
c'tor is used to put it to its place to finish the call to the function
and free all the memory used for that call.

Sometimes it is possible to avoid this copy, i.e. a compiler is allowed
to remove unnecessary copies, if e.g. the object can be constructed in
the right place during return in the called function. I think gcc-4.2
had some difficulties with optimization, so this behaviour might result
from missed optimizations. But the error message is absolutely
justified, it is just bad luck that gcc-3.4 and even gcc-4.3 do not
produce the error.

One fishy point more is omitting declarations for the friend functions
before the class, and for the declarations you need forward
declarations of the classes. I'm not fully sure, but declaring a friend
without having it declared before the class is not allowed. It cannot
work if you have template classes, because then dependent and
independent names will have to be distinguished which is only possible
with declarations before the class. For orthogonality I'd prefer adding
those declarations even here:

// declaration of friends of class TSB
class TSB;

TSB fnbase();

class TS;

TS fn();

class TSB
//-----key point 1
        friend TSB fnbase();
        friend TS fn();

Bernd Strieder

reply via email to

[Prev in Thread] Current Thread [Next in Thread]