"Victor Bazarov" <v.********@comAcast.net> wrote in message news:<6Duvb.204970$ao4.728848@attbi_s51>...
"NS Develop" <ns*********@yahoo.com> wrote... What's wrong with the following:
void SomeClass::someMethod(void)
{
A *ptrA = NULL;
ptrA = &A();
ptrA is assigned an address of a temporary variable that lives
only until the end of the expression it's used in (i.e. until
the closing semicolon). So, right after this statement 'ptrA'
is invalid.
Please forgive a perhaps foolish question. I do not have very easy
access to a bookstore to buy a hardcore C++ reference work to look
this up in.
The statement "ptrA = &A();" creates something quite different
from, say, this:
{
A a_obj; // a local variable
A *ptrA = &a_obj;
// do some stuff with ptrA
} // now a_obj is invalid
Why would one use a temporary object? It doesn't seem very
useful. Is it possible to create a temporary object in this
manner because it can be useful, or because the compiler
sometimes has to for it's own reasons, and so the syntax
is valid because of that?
If a temporary object is useful to anyone other than the
compiler, how so?
Many thanks,
Eric
....
}
where A is some class type. It seems simple, but this is giving me
unpredictable behavior.
In what sense?
Is it not just assigning ptrA to be a pointer
to a local variable?
No, there _is_ no variable. There is, OTOH, a temporary object.
Doesn't that local variable then exist within
the scope of someMethod()?
No, it does not.
Victor