Mih*_*yan 5 c++ temporary const-reference reference-binding
让我们来看看这两个功能:
std::string get_string()
{
std::string ret_value;
// Calculate ret_value ...
return ret_value;
}
void process_c_string(const char* s)
{
std::cout << s << endl;
}
Run Code Online (Sandbox Code Playgroud)
这里有两个可能的process_c_string
带有参数的调用get_string
.
没有绑定const引用的返回对象get_string
.
process_c_string(get_string().c_str());
Run Code Online (Sandbox Code Playgroud)用绑定const引用返回的对象get_string
.
const std::string& tmp_str = get_string();
process_c_string(tmp_str.c_str());
Run Code Online (Sandbox Code Playgroud)我知道第二种方式是有效的,但第一种方式是什么,标准对此案例有什么看法呢?返回的临时对象是否get_string
会在process_c_str
完成之前删除,因为没有const reference
它?
注意:这两个版本在MSVC中都可以.
临时的生命周期延长了创建它的完整表达式的长度.在您的情况下,临时将被销毁但仅在process_c_string
完成调用之后.只要该函数不存储指针供以后使用,你就可以了.
在第二种情况下(引用的绑定),该临时的生命周期被扩展为引用的范围,但在这种特定情况下,我会建议不要使用该模式.通过创建使用临时初始化的本地字符串可以获得相同的效果,并且代码更简单.(从性能的角度来看,所有编译器都会在代码中忽略潜在的额外副本,因此成本会相同)