D3V*_*1R3 5 c++ destructor arguments string-view c++17
我有一个问题,因为我不清楚函数参数何时被销毁。因此,以下 doSomething 函数的串联是否容易出错?
我问是因为“程序员有责任确保 std::string_view 的寿命不会超过指向的字符数组”。在特定情况下可以保证吗?
#include <string>
#include <string_view>
std::string doSomething(const std::string_view& str_view)
{
// do something and create a new std::string instance based on the std::string_view instance
return str;
}
int main()
{
std::string input_str{"Hello world!"};
std::string output_str{ doSomething(doSomething(doSomething(input_str))) };
return 0;
}
Run Code Online (Sandbox Code Playgroud)
const传递给(引用)参数的匿名临时变量const std::string_view& str_view在函数调用后仍然存在。
由于存在嵌套函数,因此从概念上讲,匿名临时变量不会被销毁,直到
std::string output_str{ doSomething(doSomething(doSomething(input_str))) };
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
82 次 |
| 最近记录: |