Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass temporary object to function that takes pointer

I tried following code :

#include<iostream> 
#include<string>
using namespace std;

string f1(string s)
{
   return s="f1 called";
}

void f2(string *s)
{
   cout<<*s<<endl;
}

int main()
{
   string str;
   f2(&f1(str));
}

But this code doesn't compile.
What I think is : f1 returns by value so it creates temporary, of which I am taking address and passing to f2.
Now Please explain me where I am thinking wrong?

like image 958
Happy Mittal Avatar asked Jun 06 '10 19:06

Happy Mittal


3 Answers

The unary & takes an lvalue (or a function name). Function f1() doesn't return an lvalue, it returns an rvalue (for a function that returns something, unless it returns a reference, its return value is an rvalue), so the unary & can't be applied to it.

like image 117
James McNellis Avatar answered Sep 23 '22 07:09

James McNellis


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.

like image 25
AnT Avatar answered Sep 19 '22 07:09

AnT


Your program doesn't compile because f1 has a parameter and you're not passing any.

Additionally, the value returned from a function is an rvalue, you can't take its address.

like image 29
avakar Avatar answered Sep 20 '22 07:09

avakar