Re: When may an [optimizing] C++ compiler omit object instantiations?
On Apr 22, 3:13 am, "Alf P. Steinbach" <al...@start.no> wrote:
* Kai-Uwe Bux:
blargg wrote:
[...]
*Temporary objects* are explicitly allowed to
be optimized away. Automatic objects are not.
Just to be more explicit, even temporary objects with clear
side-effects in their constructor/destructor, like printing
to cout, can be optimized.
Is that supposed to mean that
mutex_taker( g_mutex ), some_protected_expression;
is not guaranteed to acquire the mutex at the beginning of
the full expression and release it at the end? If so, I
would love to have a reference to the clause of the standard
that is responsible.
=A73.7.2/3 "If a named automatic object has initialization or a
destructor with side effects, it shall not be destroyed before
the end of the block, nor shall it be eliminated as an
optimization even if it appears to be unused, except that a
class object or its copy may be eliminated as specified in
12.8", where the reference to 12.8 is =A712.8/5 about
elimination of temporary copy construction.
As I pointed out else thread, that text is actually redundant
(not that I suggest removing it). The abstract machine
constructs and destructs the object at specific times, and a
compiler can only do differently if it can assertain that the
change does not affect the observable behavior of the program.
I.e. name that mutex and code is safe.
It's also safe as posted. The issue was actually discussed when
the lifetime of temporaries was discussed in the committee. (It
is, apparently, a common idiom, although I wouldn't use it.
When I'm counting on the existance of an object with visible
lifetime, I want that object and its lifetime to be clearly
visible to the reader.)
I'm not at all sure about the unnamed temporary, but given
that the standard explicitly addresses the issue for /named/
automatic objects, I think that the unnamed ones possibly have
lesser protection by the law...
The standard defines the lifetime of a temporary in =A712.2. This
very explicitly defines a behavior of the abstract machine. A
compiler can violate that behavior only if it can determine that
doing so does not change the observable behavior of the program.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34