Re: a question on execution order
Victor Bazarov <v.Abazarov@comAcast.net> wrote:
Mycroft Holmes wrote:
struct tricky
{
int& x;
~tricky() { x = 1234; }
};
int f()
{
int result = 6789;
tricky t = { result };
return result;
}
even if my above conjecture is correct, what if the compiler applies
NVRO and turns 'f' to something like:
void f(int& result)
{
result = 6789;
tricky t = { result };
}
I don't think NRVO has anything to do with the behaviour of 'f'.
Well, the standard 12.8/15 says that, under NRVO, the name of the local
variable being returned and the name of the variable at the call site
the result is being assigned to are treated as aliases referring to the
same object. This object is destroyed at the latter of the two times the
two objects would be destroyed had NRVO not been applied.
Without NRVO, a copy is made by the return statement, and then ~tricky
destructor acts on the original. But with NRVO, copies are elided,
there's just one object, and it appears that ~tricky destructor does
affect this object. There's nothing in the standard that says NRVO is
disallowed if some other object's destructor may have a side-effect that
affects the return value.
Since the return is by value, a temporary of type 'int' is copy-
constructed [from 'result'], so the return statement will cause
the function to return 6789.
It is true that NRVO is only applicable to objects of class type, so
having an 'int' return value clouds the issue somewhat. But consider:
struct S { int x; }
S f() {
S local = {6789};
tricky t = {local.x};
return local;
};
S global = f();
assert(global.x == 6789);
Again, according to the standard, if NRVO is applied, global and local
are two aliases for the same object. It appears that ~tricky destrutor
has no choice but to set x==1234 inside that object, which would then
trigger the assert.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925