It is possible to create (and pass) a pointer to a temporary object, assuming that you know what you are doing. However, it should be done differently.
A function with return value of non-reference type returns an rvalue. In C++ applying the built-in unary operator &
to an rvalue is prohibited. It requires an lvalue.
This means, that if you want to obtain a pointer to your temporary object, you have to do it in some other way. For example, as a two-line sequence
const string &r = f1(str);
f2(&r);
which can also be folded into a single line by using a cast
f2(&(const string &) f1(str));
In both cases above the f2
function should accept a const string *
parameter. Just a string *
as in your case won't work, unless you cast away constness from the argument (which, BTW, will make the whole thing even uglier than it already is). Although, if memory serves me, in both cases there's no guarantee that the reference is attached to the original temporary and not to a copy.
Just keep in mind though creating pointers to temporary objects is a rather dubious practice because if the obvious lifetime issues. Normally you should avoid the need to do that.