C++中,函数参数使用由临时对象返回的指针或引用,是否能安全使用(临时对象是否会提前被析构)
C++中,函数参数使用由临时对象返回的指针或引用,是否能安全使用(临时对象是否会提前被析构)
问题描述
如果在函数实参中使用临时对象A中的函数返回另一个临时对象B,临时对象A会在进入函数前析构还是在离开函数后析构
问题来源
在写leetcode1154题时,写到代码
class Solution {
public:
int dayOfYear(string date) {
...
int year = atoi(date.substr(0, 4).c_str());
int mouth = atoi(date.substr(5, 2).c_str());
int day = atoi(date.substr(8, 2).c_str());
...
}
};
由于std::string().c_str()
返回的是std:;string()
对象中的字符数组指针,由此想到是否将该指针传入atoi()
函数后,临时对象析构导致使用空悬指针。
编写测试代码
编写如下代码进行测试:
#include <iostream>
class foo
{
public:
foo() {
std::cout << "construct" << std::endl;
}
~foo() {
std::cout << "destruct" << std::endl;
}
int get1() {
return 1;
}
};
void bar(int i)
{
std::cout << "function begin" << std::endl;
std::cout << "function end" << std::endl;
}
int main()
{
bar(foo().get1());
return 0;
}
运行结果:
考虑到此问题与运行运行环境相关较小,避免信息冗余,不对运行环境进行描述。
运行结果如下:
ubuntu2004@DESKTOP-RKPEPDU:~/code/cpp$ ./test_temp_object_life
construct
function begin
function end
destruct
ubuntu2004@DESKTOP-RKPEPDU:~/code/cpp$
结果分析
可以看到,传入的临时对象A在函数离开后才析构,所以,使用临时对象函数返回的指针是安全的。