Pass temporary object to function that takes pointer

不羁岁月 提交于 2019-12-18 06:14:41

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


Try this:

int main()
{
    string str;
    string str2 = f1(str); // copy the temporary
    f2(&str2);
}


来源:https://stackoverflow.com/questions/2985571/pass-temporary-object-to-function-that-takes-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!