Board index » cppbuilder » References & Pointers

References & Pointers

Hello Everyone,

 I'm not up to speed on references and pointers,
but wondering if anyone can give an explanation
of why there are differences between creating
an instance of TRegistry and TIniFile.

TRegistry& regkey1=*new TRegistry();

but for TIniFile,

TIniFile *inifile1=new TIniFile(defaults);

and when using;

regkey1.ReadString(..);

but for TIniFile,

inifile1->ReadString(..);

Thanks in advance,
Regards Digby Millikan.

 

Re:References & Pointers


Quote
Digby Millikan <di...@bold.net.au> wrote in message

news:8757bq$2nh4@bornews.borland.com...

Quote
>  I'm not up to speed on references and pointers,
> but wondering if anyone can give an explanation
> of why there are differences between creating
> an instance of TRegistry and TIniFile.

> TRegistry& regkey1=*new TRegistry();

> but for TIniFile,

> TIniFile *inifile1=new TIniFile(defaults);

> and when using;

> regkey1.ReadString(..);

> but for TIniFile,

> inifile1->ReadString(..);

There is no real difference here.  The first example could be also written
this way.
TRegistry * regkey1 = new TRegistry();
regkey1->ReadString(..);

It's a little more complicated than this, but a reference can be thought of
as simply an automatically dereferenced pointer.  Syntactic sugar, as some
call it.  It's kind of like using a pointer like this, where a reference
automatically inserts the (*ptr).

TRegistry * regkey1 = new TRegistry();
(*regkey1).ReadString(..);

One of the primary differences between pointers and references is that
references must always be initialized.
int i;
int & j = i;  // ok
int & k;  // not ok

int p;
int * q = &p  // ok
int * r;  // ok
r = &p;  // ok

In general, I personally would consider a construct like the following to be
in bad form.  If it's a pointer, just use it as a pointer.
TRegistry& regkey1=*new TRegistry();

The only time I would dereference a pointer and allow it to be assigned to a
reference is when a function takes a reference and I have a pointer.  IMO,
references are really to be used to keep the amount of information being
passed on the stack down and to keep the creation of unnecessary temporaries
to a minimum.
class T
{

Quote
};

void func(const T & ref);

void func(const T & ref)
{

Quote
};

void func1()
{
   T * t = new T;
   func(*t);
   delete t;

Quote
};

The only other time I have explicitly used references is in a complex
function that deals with a particular portion of complex data structure.  I
have been known to set a reference at the top to a convenient point in the
data structure to cut down on the line lengths and therefore try to improve
the readability of the rest of the function.

Ty Adams

Other Threads