I’m trying to find out when temporary variables are released. I wrote the code below.
#include <stdio.h>
class C
{
public:
C()
{
printf("C O\n");
}
C(const C&)
{
printf("C& O\n");
}
virtual ~C()
{
printf("C D\n");
}
};
int kkk(const C&)
{
printf("kkk\n");
return 0;
}
int kkk2(int)
{
printf("kkk2\n");
return 0;
}
int main()
{
(kkk2( kkk2( (kkk(C()),3) ) ), printf("dsfsdfs\n"), true) && (printf("dsdddf\n"),true);
printf("=====\n");
return 0;
}
I expect Class C to be released after kkk is called, but actually, the result is:
C O
kkk
kkk2
kkk2
dsfsdfs
dsdddf
C D
=====
I run the code with g++ clang++ and msvc++, the result is same. Class C is release at the end of a statement.
Is it a C++ standard to release temporary variables at the end of a statement?
>Solution :
From Temporary_object_lifetime
All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation. This is true even if that evaluation ends in throwing an exception.
There are two exceptions from that:
[..]
So to answer your question:
Is it a C++ standard to release temporary variables at the end of a sentence?
Yes, temporaries are destroyed at end of full-expression (not sentence).