public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
From: David Fang <fang@csl.cornell.edu>
To: "michid@gmail.com" <michid@gmail.com>
Cc: <gcc-help@gcc.gnu.org>
Subject: Re: Wrong virtual method called (bug?)
Date: Wed, 12 Jul 2006 20:37:00 -0000	[thread overview]
Message-ID: <20060712163300.T24362-100000@maxwell.csl.cornell.edu> (raw)
In-Reply-To: <44B55CBA.5040500@gmail.com>

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



      reply	other threads:[~2006-07-12 20:37 UTC|newest]

Thread overview: 2+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2006-07-12 20:29 michid
2006-07-12 20:37 ` David Fang [this message]

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20060712163300.T24362-100000@maxwell.csl.cornell.edu \
    --to=fang@csl.cornell.edu \
    --cc=gcc-help@gcc.gnu.org \
    --cc=michid@gmail.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
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).