문제

In regards to when temporary objects get destroyed, is this valid:

FILE *f = fopen (std::string ("my_path").c_str (), "r");

Will the temporary be destroyed immediately after having evaluated the first argument to fopen or after the fopen call.

Testing with the following code:

#include <cstdio>
using namespace std;
struct A {
        ~A() { printf ("~A\n"); }
        const char *c_str () { return "c_str"; }
};
void foo (const char *s) { printf ("%s\n", s); }
int main () {
        foo (A().c_str());
        printf ("after\n");
        return 0;
}

gives:

c_str
~A
after

which indicates that the whole statement is first evaluated, and then any temporaries are destroyed. Is this ordering mandated by the standard or implementation-specific?

도움이 되었습니까?

해결책

The temporary will be destroyed at the end of the expression, namely the ; semicolon. So you are safe.

§ 12.2 ... Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception.

다른 팁

Is this ordering mandated by the standard or implementation-specific?

[class.temporary]/3

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

so its mandated by the standard

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top