emerth said:
"Victor Bazarov" <
[email protected]> wrote in message
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
Correct. As a matter of fact, as Victor pointed out, the
first form is not valid at all (taking address of a temporary).
Why would one use a temporary object? It doesn't seem very
useful.
It can sometimes be, especially as part of a larger
expression.
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,
Yes, many expressions can cause creation of a temporary
object.
and so the syntax
is valid because of that?
The OP's syntax is not valid, your example is (but doesn't
really do anything useful.)
If a temporary object is useful to anyone other than the
compiler, how so?
Contrived example:
Suppose I want to output two items with a certain number
of space characters between them:
std::string s1 = "ABC";
std::string s2 = "XYZ";
std::cout << s1 << std::string(10, ' ') << 's2' << '\n';
/* prints "ABC XYZ" */
The expression std::string(10, ' ')
creates a temporary string object containing ten spaces.
After the statement, the temporary string is destroyed.
-Mike