有一段代码如下所示,按照之前的理解,A()对象进入函数体之前会析构,程序应该会崩溃。
```c++
#include <unistd.h>
using namespace std;
class A {
private:
string a;
public:
A()
: a("123")
{
cout << "Build" << endl;
}
const char* get() { return a.c_str(); }
~A() { cout << "Destroy" << endl; }
};
void pt(const char* p)
{
cout << "456" << endl;
int i = 0;
while (i < 10) {
sleep(1);
++i;
}
cout << p << endl;
}
int main()
{
pt(A().get());
}
运行结果如下:
```c++
Build
456
123
Destroy
并没有崩溃,好像函数调用也是一个表达式,所以只有函数调用完毕后才会释放临时对象?查了很多资料不是很清楚,望解答。
我写了个测试:
#include<iostream>
using namespace std;
class A
{
public:
A()
{
printf("Create A\n");
}
~A()
{
printf("Destroy A\n");
}
int func()
{
return 0;
}
};
void print(int n)
{
printf("input print func\n");
}
int main()
{
print(A().func());
printf("out print func\n");
return 0;
}
运行结果:
结论:你的代码运行没有问题,虽然A是一个临时变量,但是也要等到函数执行完了才会析构。