Re: Function arguments and temporaries
rado wrote:
Imagine this:
void f (int*);
f (boost::shared_ptr <int> (new int).get());
Just curious, but what are you sharing the pointer with? The
use of shared_ptr seems kind of misleading here -- wouldn't
scoped_ptr express more accurately (to the reader, anyway) what
you are trying to do.
Is there a guarantee that f() will not be passed a dangling
pointer? In other words, will the temporary shared_ptr still
exist while within f()?
The temporary will exist until the end of the full expression.
This might or might not be long enough -- if f stores the
pointer somewhere, for example, for later use, you will have a
dangling pointer.
I chose shared_ptr for illustration only, just imagine any
temporary. Also note that it is *not* the shared ptr that is
passed, but the result of .get() on a temporary.
OK. I take back my comment above:-).
The classical example for this problem, of course, is something
like:
std::ofstream f( (filename + ".doh").c_str() ) ;
The answer is, as I said, that the temporary will last until the
end of the full expression. Or a little bit longer, in a few
specific cases. (My example is actually one of them -- the
temporary will last until the constructor of f returns, even
though the constructor of f is not part of the full expression.)
This example actually raises another question: I'm not actually
sure that the standard guarantees that ofstream won't save the
char const* somewhere, and use it later (although I'm pretty
sure that this was the intent -- and no implementation I know of
does do this). If it does, of course, the above won't work.
--
James Kanze kanze.james@neuf.fr
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]