C ++返回临时对象的混乱 [英] C++ returning temporary objects confusion
问题描述
我有一个相当基本的C ++问题,考虑一个函数,该函数需要一些输入参数,并根据如下参数创建一个std::string
:
std::string constructString( int some_parameter ) {
std::stringstream ss;
// Construct a string (arbitrarily complex)
ss << "Some parameter is " << some_parameter << " right now";
return ss.str(); //Am I not returning a temporary object here?
}
我知道当函数返回时,stringstream-object将超出范围,但这也不会使构造的字符串无效吗?
如果我将返回类型更改为const char *
却返回了ss.str().c_str()
会发生什么?
上面的代码似乎可以正常工作,但是我怀疑那是因为当我使用它时,包含临时"对象的内存还没有被其他东西覆盖吗?
我必须承认,在这样的情况下,我通常会感到困惑,如果有人可以向我解释整个临时对象"(或者只是将我指出正确的方向),我将不胜感激./p>
提前谢谢
您将返回一个临时对象,但是由于按值返回它,因此将创建副本.如果返回指针或对临时对象的引用,那将是一个错误.
如果将返回类型更改为const char *
并返回ss.str().c_str()
,您将返回指向ss.str()
返回的临时std::string
缓冲区的指针,那将是不好的.
I've got a rather basic C++ question, consider a function that takes some input parameters and creates a std::string
from those parameters like the one below:
std::string constructString( int some_parameter ) {
std::stringstream ss;
// Construct a string (arbitrarily complex)
ss << "Some parameter is " << some_parameter << " right now";
return ss.str(); //Am I not returning a temporary object here?
}
I understand that the stringstream-object will go out of scope when the function returns, but doesn't that invalidate the constructed string as well?
What would happen if I changed the return type to const char *
and returned ss.str().c_str()
instead?
Code like the above seems to work, but I suspect that's just because the memory containing the 'temporary' object has not yet been overwritten with something else when I use it?
I have to admit, I'm rather confused in such situations in general, I'd appreciate it if someone could explain this whole "temporary objects"-thing to me (or just point me in the right direction).
thx in advance
You are returning a temporary object, but because you return it by value, the copy is created. If you return pointer or reference to temporary object, that would be a mistake.
If you change the return type to const char *
and return ss.str().c_str()
you would return pointer to some buffer of temporary std::string
returned by ss.str()
and that would be bad.
这篇关于C ++返回临时对象的混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!