https://gcc.gnu.org/bugzilla/show_bug.cgi?id=26388

--- Comment #14 from Martin Sebor <msebor at gcc dot gnu.org> ---
I agree with the goal of making containers efficient so please take this as
constructive criticism.

Jonathan and I discussed this on IRC a bit yesterday and I've thought about it
some more since then.  I'm unconvinced the suggested optimization would be
valid (conforming).  To Marc's point in comment #11, the default vector was
never intended to be stack-based and I'm not aware of any change in the
standard that would make it valid to allocate it on the stack.  To Jonathan's
point in comment #12, "eventually" means that creating one or more non-empty
vectors can be expected by a conforming program to cause at least one call to
operator new.

Beyond conformance, another, arguably even more important, point to consider is
that vector is required to throw an exception when memory is exhausted. 
Implementing it to live on the stack (and allocate memory via alloca) would
either violate that requirement, letting it exhaust the stack and crash the
program, or mean checking the amount of available stack space on every
allocation (or just the first allocation).  Alternatively, it would mean gating
the optimization on known sizes of the vector that were less than some small
constant maximum (i.e., effectively turning std::vector into std::array.)

Jonathan also reminded me that vectors A and B must satisfy the "i = A.begin();
A.swap (B); assert (i == B.begin())" postcondition, with swap having constant
complexity.  A vector allocated on the stack would not, in general, be able to
satisfy these requirements.  It couldn't be swapped with or moved in constant
time to another vector with a different lifetime, further constraining the
optimization.

There may be clever ways to overcome these problems, either by making the
implementation more complex, or by relaxing the standard requirements on
implementations, or (likely both), but they would have costs of their own.  The
former likely in efficiency and significant complexity, and the latter in
constraining programs (i.e., breaking some that are now valid).

So in summary, while I would like to see STL containers be as efficient as they
can be (and have, in fact, been thinking and talking with Jeff about how to
improve them to this end), I don't think this optimization is viable.  It may
be unfortunate but it is the price of generality, customizability, and
conformance.

Reply via email to