dangling reference

N

Nick Keighley

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?
 
M

Marcin Kalicinski

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top