G++: Non-const copy ctor sometimes ignored
Martin v. Loewis
martin@loewis.home.cs.tu-berlin.de
Sun Feb 27 15:17:00 GMT 2000
> | 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
More information about the Gcc-bugs
mailing list