dangling reference

Discussion in 'C++' started by Nick Keighley, Apr 3, 2005.

  1. I saw this in some code I'm maintaining. Is it a bad idea?


    class T
    {
    public #:
    T () i_mem(0)
    { }

    T (T2 &t2) i_mem(0), t2_ref (t2)
    { }


    private:
    int i_mem;
    T2 &t2_ref;
    }

    This is from memory and the real code compiles so any syntax errors
    are my fault. It also had destructors, copy constructors etc.

    What bothered me was the apparently uninitialised reference in the
    default constructor.

    If it were a pointer then would it be initialised to NULL by default?

    But a reference *must* reference something?


    --
    Nick Keighley
    Nick Keighley, Apr 3, 2005
    #1
    1. Advertising

  2. > class T
    > {
    > public #:
    > T () i_mem(0)
    > { }
    >
    > T (T2 &t2) i_mem(0), t2_ref (t2)
    > { }
    >
    >
    > private:
    > int i_mem;
    > T2 &t2_ref;
    > }
    >
    > This is from memory and the real code compiles so any syntax errors
    > are my fault. It also had destructors, copy constructors etc.


    This code should not compile, because the all member references must be
    initialized in constructor initializer list. What might be happening in your
    case (you say it compiles) is that class T is actually a template
    parametrized on T2 type. If so, you might not get error unless default
    constructor is actually used. I don't know if this is mandated by the
    standard, but at least Visual C++ .NET behaves this way.

    cheers,
    Marcin
    Marcin Kalicinski, Apr 3, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. rootz anabo
    Replies:
    0
    Views:
    448
    rootz anabo
    Feb 3, 2005
  2. Hans Van den Eynden

    dangling reference

    Hans Van den Eynden, Oct 16, 2004, in forum: Java
    Replies:
    1
    Views:
    2,837
    Joona I Palaste
    Oct 16, 2004
  3. kaede

    Dangling Reference

    kaede, Oct 27, 2003, in forum: C++
    Replies:
    4
    Views:
    409
    lilburne
    Oct 28, 2003
  4. Hans Van den Eynden

    dangling reference

    Hans Van den Eynden, Oct 14, 2004, in forum: C++
    Replies:
    5
    Views:
    403
  5. Belebele

    Dangling Reference. Idiom

    Belebele, Feb 7, 2007, in forum: C++
    Replies:
    10
    Views:
    542
    Grizlyk
    Feb 8, 2007
Loading...

Share This Page