Temporary variable is a variable that is released if there is no variable to receive it
class A
{
public:
A()
{
std::cout << " 1 A() \n";
}
A(const A& aa)
{ std::cout << "copy construction\n"; }
~A()
{
std::cout << " 2 ~A() \n";
}
};
//When the type returned by the function is a value, the return is a temporary variable
A TestA()
{
return A();
}
//When the variable is returned, the copy structure will be called to generate a temporary variable
A TestA2()
{
A aa1= A();
return aa1;
}
int main()
{ A(); //Release if there is no variable receiving
TestA();
system("pause");
}
When returning variables, it’s best to return temporary variables or references instead of variables.