将临时对象传递给采用指针的函数
我尝试了以下代码:
#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));
}
但此代码无法编译。
我的想法是:f1 按值返回,因此它创建临时的,我正在获取其中的地址并传递给 f2。
现在请解释一下我的想法错在哪里?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设您知道自己在做什么,则可以创建(并传递)指向临时对象的指针。然而,应该采取不同的做法。
具有非引用类型返回值的函数返回右值。在 C++ 中,禁止将内置一元运算符
&
应用于右值。它需要一个左值。这意味着,如果您想获取指向临时对象的指针,则必须以其他方式完成。例如,作为两行序列
,也可以通过使用强制转换将其折叠为单行
在上述两种情况下,
f2
函数都应接受const string *
参数。在您的情况下,只有一个string *
是行不通的,除非您放弃参数的常量性(顺便说一句,这将使整个事情比现在更加丑陋)。不过,如果我没记错的话,在这两种情况下都不能保证引用附加到原始临时文件而不是副本。请记住,尽管创建指向临时对象的指针是一种相当可疑的做法,因为如果存在明显的生命周期问题。通常您应该避免这样做。
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
which can also be folded into a single line by using a cast
In both cases above the
f2
function should accept aconst string *
parameter. Just astring *
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.
一元
&
采用左值(或函数名称)。函数f1()
不返回左值,它返回右值(对于返回某些内容的函数,除非返回引用,否则其返回值是右值),因此一元&
无法应用于它。The unary
&
takes an lvalue (or a function name). Functionf1()
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.您的程序无法编译,因为
f1
有一个参数,而您没有传递任何参数。此外,函数返回的值是右值,您无法获取其地址。
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.
试试这个:
Try this: