Destructor call in a comma-separated expression

早过忘川 提交于 2019-12-21 10:16:34

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/44309451/destructor-call-in-a-comma-separated-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!