Richard Li wrote:

Right, page 211 of the C++ standard (2003) explains when copy-ctor and
dtor are allowed to be optimized away. But the two circumstances are
both like this:
A is constructed; A is copy-constructed to B; A is destructed
Here A is a temporary object in some sense, and the standard allows
for directly constructing B.
However, Neal expected the compiler to optimize "A is constructed; A
is destructed" away. I find nowhere in the standard that allows this.

I think it would fall under the "as-if" rule. The special rules you mention are only necessary if it causes a behavior change.

I think the biggest problem here is that GCC will not elide calls to the allocator. This is a subject of some controversy--even though its probably difficult to do such optimization anyway. It's not quite clear that such optimization is legal under the as-if rule.

For example, the code you have written will throw std::bad_alloc if your system is out of memory. The code that you would like it to be optimized to would not do that, which is a behavior change.

This has been discussed a few times before. See, for example, this thread <http://gcc.gnu.org/ml/gcc-patches/2003-11/msg00564.html>.

So, you should probably never count on an optimizer removing calls to anything that touches memory management. What's usually done, as Richard Li points out, is to write your code in such a way that such optimization is not necessary.

Reply via email to