- Temporary objects
Temporary objects
#include<iostream>
class temporary{
public:
temporary(){
std::cout << "temporary ctor" <<std::endl;
}
~temporary(){
std::cout << "destory" <<std::endl;
}
void fun(){
std::cout << "This is function output" <<std::endl;
}
};
int main(){
temporary ().fun();
return 0;
}
output:
temporary ctor
This is function output
destory
- A temporary object is created when you create an unnamed non-heap object, i.e. an anonymous object
Integer inte= Integer(5); //initialize an object with an unnamed temporary object
- When a constructor acts as an implicit type conversion, a temporary object is created and passed to the function as the argument.
class Integer
{
public:
Integer(int i):m_val(i){}
~Integer(){}
private:
int m_val;
};
void testFunc(Integer itgr)
{
//do something
}
int i = 10;
testFunc(i);
A temporary object is created and passed as the argument to testFunc.
- When a function returns an object, a temporary object is created: it is constructed by the copy constructor with the returned object as the argument.
Integer Func()
{
Integer itgr;
return itgr;
}
int main()
{
Integer in;
in = Func();
}
Why we need function-like class?
- An instance of the class can be passed around as an argument (the class can be changed at any time without affecting other classes or functions)

- The standard library contains many functors, and they inherit from various curious base classes