如果没有const引用

如果没有const引用

本文介绍了如果没有const引用,临时对象会被删除吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看看这两个函数:

  std :: string get_string()
{
std :: string ret_value;
//计算ret_value ...
return ret_value;
}

void process_c_string(const char * s)
{
std :: cout< s<< endl
}

这里有两个可能的调用: process_c_string 使用 get_string 返回的参数。


  1. 绑定对 get_string 的返回对象的const引用。

      process_c_string ().c_str()); 


  2. 使用绑定const引用 get_string

      const std :: string& tmp_str = get_string(); 
    process_c_string(tmp_str.c_str());


我知道第二种方式有效,第一个,什么标准说这个案件?将在 process_c_str 之前删除 get_string 返回的临时对象,因为没有 const

$ ms $。 b

解决方案

临时的生命周期延伸到创建它的完整表达式的长度。在你的情况下,临时将被销毁,但只有在调用 process_c_string 完成后。



在第二种情况(引用的绑定)中,该临时的生命周期被延长作为参考的范围,但我建议在这种特殊情况下反对这种模式。你通过创建一个本地字符串初始化与临时和相同的效果,代码更简单。 (从性能的角度来看,所有编译器在代码中删除潜在的额外副本,因此成本是一样的)


Lets take a look to this two functions:

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;
}

And here are two possible calls of process_c_string with argument returned by get_string.

  1. Without binding const reference to the returned object of get_string.

    process_c_string(get_string().c_str());
    

  2. With binding const reference to the returned object of get_string.

    const std::string& tmp_str = get_string();
    process_c_string(tmp_str.c_str());
    

I know that second way is valid, but what about the first one, what does standard say about this case? Will the temporary object returned by get_string be deleted before process_c_str finished because of there is no const reference to it?

Note: The both versions are ok in MSVC.

解决方案

The lifetime of the temporary extends for the length of the full expression in which it was created. In your case, the temporary will be destroyed but only after the call to process_c_string completes. As long as the function does not store the pointer for later use, you are fine.

In the second case (binding of reference), the lifetime of that temporary is extended to be the scope of the reference, but I would advise against that pattern in this particular case. You get the same effect by creating a local string initialized with the temporary and the code is simpler. (From a performance point of view, all compilers elide the potential extra copy in the code, so the cost would be the same)

这篇关于如果没有const引用,临时对象会被删除吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 13:53