Temporary objects are created by compiler to store temporary values which are needed for a short period of time. For example, returning value from a function.

When function returns, the returning value will be destroyed at the end of the function. So, a temporary object with the returning value (being copied) is created and returned back to the caller. For example,

int getSomeValue()
{
    int value{2};
    return value;
}
 
int main()
{
    std::cout << getSomeValue();
    return 0;
}

Here, as value would be destroyed at the function end, compiler creates a temporary object with the value of the variable value being copied and returns back to the caller, which again gets destroyed at the end of full expression.

For example, temporary object created would be destroyed after std::cout << getSomeValue(); executes.

Note

In modern C++ compilers, this intermediary temporary objects such as returning from the function would be skipped and returned value would directly be used.

So, in above example, as return value from getSomeValue is immediately getting used, so the compiler would skip the creation and destruction of temporary object.

References

  1. https://www.learncpp.com/cpp-tutorial/introduction-to-local-scope/#temporaries