Re: Length of C++ arrays allocated by operator new[]
On 21.08.11 23.32, Leigh Johnston wrote:
- The old platform does not support STL well.
I don't care about old platforms unless I am being paid to care about
old platforms.
:-)
- STL causes the executable size to explode. One disadvantage of
template meta programming over generics. (Of course, there are many
advantages on the other side.)
Template code bloat is mostly over stated; non-template classes with
lots of inline functions can have similar "bloat".
That's not what I mean. The most bloat comes from different
instantiations of template classes that in fact produce binary the same
code. E.g. std::vector will most likely result in identical code for all
pointer types (except for member function pointers, of course).
At least I have not seen a compiler that can share code between
different template instantiations.
std::vector has the major disadvantage that any piece of code that has
write access to its elements can also change its size and, more
importantly, cause reallocations. That's sometimes not wanted and could
cause hard to find bugs with UB, especially if the array is shared
between threads.
If you are worried about clients changing a vector's size then don't
expose the vector by, for example, using private inheritance (as Ian
said in his reply) or composition.
I ended up with my own class, which is trivial for arrays that are not
resizable.
about the only case where one still needs to use dynamic
arrays is if you want to allocate but not initialize a buffer.
Why? vector will always initialize /less/ or same than operator new[].
The allocation size of the vector may be larger than logical size,
containing additional uninitialized storage. new[] in contrast always
invokes the standard constructors (if any).
Wrong; for POD and built-in types new[] can allocate storage but not
initialize it at all; whilst a vector with N elements will have
initialized them all:
So vector<char> initializes the storage? To zero I guess. I was not
aware of that.
Marcel