究竟什么时候函数参数被破坏?
When exactly are function arguments being destructed?
我有一个问题,因为我不清楚函数参数何时被销毁。那么,下面的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;
}
传递给(const
引用)参数的匿名临时变量 const std::string_view& str_view
在函数调用后仍然存在。
由于存在嵌套函数,因此从概念上讲,直到
的结束分号才会销毁匿名临时对象
std::string output_str{ doSomething(doSomething(doSomething(input_str))) };
我有一个问题,因为我不清楚函数参数何时被销毁。那么,下面的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;
}
传递给(const
引用)参数的匿名临时变量 const std::string_view& str_view
在函数调用后仍然存在。
由于存在嵌套函数,因此从概念上讲,直到
的结束分号才会销毁匿名临时对象std::string output_str{ doSomething(doSomething(doSomething(input_str))) };