Re: Wrong virtual method called (bug?)

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

 



Hi,
	Your code looks suspicious, explained below.

On Wed, 12 Jul 2006, michid@xxxxxxxxx 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




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux