Re: Check if an argument is temporary
On Oct 29, 3:29 am, "Daniel T." <danie...@earthlink.net> wrote:
Klaas Vantournhout <no_valid_em...@spam.com> wrote:
I was wondering if it is possible if you can check in a function if one
of the arguments is temporary.
What I mean is the following. A is a class, foo is a function returning
a class and bar is a function using A is an argument returning something
else
class A;
A foo(void);
int bar(const A&);
int main(void) {
std::cout << bar(foo());
return 0;
}
In the above piece of code, the object returned by foo is temporary and
destroyed after bar is finished with it.
The question is, is it possible to distinguish in bar if its argument is
such a temporary object or not?
Not portably. If you know enough about the system you are on, you can
tell from the address if it is in the heap or on the stack, but that's
about it.
That wouldn't help, since local variables are also on the stack.
An obvious solution would be to have a separate argument in
'bar()' to tell the function if the object passed in is a temp
or not. :-)
Overloading on a const reference and a non-const reference might
be sufficient. A const variable will still bind to the const
reference, like a temporary, but a non-const variable will bind
to the non-const reference.
The real question is why the OP wants to know. There's likely a
solution to his real problem which doesn't require such
knowledge.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34