* Wrong virtual method called (bug?)
@ 2006-07-12 20:29 michid
2006-07-12 20:37 ` David Fang
0 siblings, 1 reply; 2+ messages in thread
From: michid @ 2006-07-12 20:29 UTC (permalink / raw)
To: gcc-help
The following program gives different output on g++ 3.3.6 and 4.0.3.
With 3.3.6 it prints
D::foo()
D::foo()
with 4.0.3 it prints
C::foo()
D::foo()
which is what I'd expected it to print. Is this a known issue?
Michael
#include <iostream>
using namespace std;
struct B {
virtual void foo() const = 0;
};
struct C: B {
virtual void foo() const { cout << "C::foo()" << endl; }
};
struct D: B {
virtual void foo() const { cout << "D::foo()" << endl; }
};
struct A {
const B &b;
A(const B& x = C()): b(x) {}
void foo() { b.foo(); }
};
int main() {
A a1 = A(C());
A a2 = A(D());
a1.foo();
a2.foo();
return 0;
}
^ permalink raw reply [flat|nested] 2+ messages in thread
* Re: Wrong virtual method called (bug?)
2006-07-12 20:29 Wrong virtual method called (bug?) michid
@ 2006-07-12 20:37 ` David Fang
0 siblings, 0 replies; 2+ messages in thread
From: David Fang @ 2006-07-12 20:37 UTC (permalink / raw)
To: michid; +Cc: gcc-help
Hi,
Your code looks suspicious, explained below.
On Wed, 12 Jul 2006, michid@gmail.com wrote:
> The following program gives different output on g++ 3.3.6 and 4.0.3.
> With 3.3.6 it prints
>
> D::foo()
> D::foo()
>
> with 4.0.3 it prints
>
> C::foo()
> D::foo()
>
> which is what I'd expected it to print. Is this a known issue?
>
> Michael
> #include <iostream>
> using namespace std;
>
> struct B {
> virtual void foo() const = 0;
> };
>
> struct C: B {
> virtual void foo() const { cout << "C::foo()" << endl; }
> };
>
> struct D: B {
> virtual void foo() const { cout << "D::foo()" << endl; }
> };
>
> struct A {
> const B &b;
> A(const B& x = C()): b(x) {}
HERE: parameter x (and member b) are initialized by reference to a
temporary (automatic) object of type C. In other words, it is probably
being destroyed, leaving a dangling reference. Thus, the behavior is
undefined.
> void foo() { b.foo(); }
> };
>
> int main() {
> A a1 = A(C()); // C is dead!
> A a2 = A(D()); // so is D!
> a1.foo();
> a2.foo();
> return 0;
> }
If I had to guess why there are different results:
C and D can either be allocated the same slot on the stack or different,
entirely compiler/optimization dependent.
Fang
^ permalink raw reply [flat|nested] 2+ messages in thread
end of thread, other threads:[~2006-07-12 20:37 UTC | newest]
Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2006-07-12 20:29 Wrong virtual method called (bug?) michid
2006-07-12 20:37 ` David Fang
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).