Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Are temporary variables released at the end of a statement?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading