Re: container memory control for C++
Mathias Gaunard ha scritto:
On May 17, 8:59 am, Alberto Ganesh Barbati <AlbertoBarb...@libero.it>
wrote:
Yes, that tricks makes only one copy of the whole container. That means
it has to copy every element inside the container. That why I said
"copies". The point is that if the element type had a move constructor,
an optimized implementation of trim() might use it and avoid the copies.
No. As I said, there is no way to do that unless allocators provide in-
place shrinking.
You need to copy to shrink, that's it. That's what you don't seem to
understand.
And I don't see how it is related to move constructors at all.
With move constructors, you can achieve shrinking by doing this:
1) allocate a new, smaller buffer (the "new" buffer)
2) use move constructors to initialize every element of the new buffer
from every element of the "old" buffer
3) change the internal pointer so that it points to the new buffer
4) destroy the elements of the old buffer
5) deallocate the old buffer
That's essentially the same as doing a copy, except that it uses move
constructors instead of copy constructors. The only concern is what
happens if a move constructor throws, as the contents of the old buffer
are lost during the process and so we cannot "rollback" the operation.
However, if the move constructor does not throw (a requirement that is
usually easy to achieve) then there is no problem at all. The committee
seems to think that this additional requirement is acceptable, as the
latest draft of the standard includes explicit reference to it (see for
example 23.2.5.2/2).
I agree that having in-place shrinking allocators would be optimal, as
it would avoid even the alloc/move/destroy/free cycle, but as you can
see the copy *can* be avoided in C++0x and the latest draft provides
wording to allow such optimization.
Regards,
Ganesh
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]