Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor call in a comma-separated expression

consider the following example program:

#include <iostream>
using namespace std;
struct t
{
    ~t() {cout << "destroyed\n"; }
};
int main()
{
    cout << "test\n";
    t(), cout << "doing stuff\n";
    cout << "end\n";
}

The output I get with GCC 4.9.2 is:

test 
doing stuff 
destroyed 
end

cpp.sh link: http://cpp.sh/3cvm

However according to cppreference about the comma operator:

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded, and its side effects are completed before evaluation of the expression E2 begins

I'd expect ~t() to be called before cout << "doing stuff"

Is this a standard behavior? If so, where is it defined in the standard?

like image 294
Nyashes Avatar asked Jun 01 '17 13:06

Nyashes


2 Answers

"Its result is discarded" means that the subexpression's value (here of type t) is ignored.

Its lifetime, however, is unaffected: as any all temporaries, it is destructed at the end of the full-expression (i.e. the semicolon here).

like image 140
Quentin Avatar answered Oct 27 '22 08:10

Quentin


The cppreference wording here is unfortunate.

As with any temporary, this one will last until the end of the full-expression in which it appears.

By "side effects" it is talking about the construction of the temporary.

like image 40
Lightness Races in Orbit Avatar answered Oct 27 '22 10:10

Lightness Races in Orbit