What determines when a destructor is called for a temporary object in C++?

Guys I've asked few days ago a question and didn't have really time to check it and think about it, but now I've tried one of the solutions and I can't understand why does it work? I mean why destructor is called at the end of line like this:

#include "stdafx.h"
#include "coutn.h"
#define  coutn coutn()
int _tmain(int argc, _TCHAR* argv[])
{
    coutn << "Line one " << 1;//WHY DTOR IS CALLED HERE
    coutn << "Line two " << " and some text.";
    return 0;
}

I assume that it has something to do with lifetime of an object but I'm not sure what and how. As I think of it there are two unnamed objects created but they do not go out of scope so I can't understand for what reason is dtor called.
Thank you.

Upvotes: 1

Views: 512

Answers (2)

fredoverflow
fredoverflow

Reputation: 263078

The standard says:

Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created.

A full-expression is an expression that is not a subexpression of another expression

Upvotes: 6

Peter Alexander
Peter Alexander

Reputation: 54270

coutn() create a temporary object, which will be destroyed at the next sequence point (the end of the line in this case).

Upvotes: 7

Related Questions