This is the mail archive of the gcc-bugs@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]

Re: G++: Non-const copy ctor sometimes ignored


> | class B;
> | class A {
> |   public:
> |     A()		 {}
> |     A(const A &) {}
> |     A(B &)	 {}
> | };
> | class B {
> |   public:
> |     B()		 {}
> |     B(B &)	 {}
> |     B(const A &) {}
> | 
> |     // Uncomment the following line and the error goes away:
> |     //B(const B &) {}
> | };
> | 
> | B func() { return A(); }
> 
> Here, AFAICT B::B(const A&) should be used to initialize the returned
> value. So g++ should accept the code.  So this is a bug in the
> front-end. 

No, it's a bug in the code. B(const A&) is used to initialize the
temporary in the return statement. You then need to copy the temporary
using a copy ctor - returning from a function is copy-initialization,
not direct-initialization; i.e. this is equivalent to

  B result = A();

and different from

  B b((0,A()));

which would indeed use B(A const&); 

You cannot initialize the return value, because the temporary B object
cannot be bound to a reference, and because there is no implicit
B(const B&) copy ctor.

The compiler has the option to elide the final call to the copy ctor -
it still has to check whether the programm is well-formed if the copy
ctor was called.

Welcome to C++,
Martin


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