Re: Need to understand tradeoff between array and vector
James Kanze wrote:
and completely non-equivalent to the former.
And just how is
std::vector< int > array( 3 ) ;
different from the former? Except that it doesn't convert into
a pointer (and thus loose the size), and that it is correctly
initialized. (Both fundamental advantages.)
Its size is different, it doesn't store the values inside the owning
class but elsewhere, copying it is internally a rather different (and
heavier, especially for arrays of 3 integer elements) operation...
In general: use a C style array if you need static
initialization (in an object with static lifetime), or possible,
for very small arrays in frequently used objects, if you expect
to see lots and lots of short lived instances of those objects.
Otherwise, use std::vector.
If the size of the array is fixed (and known at compile time), and
each instance of the class will have its own private array (ie. it won't
be shared among objects in any way), I see little reason to not to use a
C-style array rather than std::vector. Regardless of the size of the
array, it will consume less memory and be more efficient (of course the
larger the array, the smaller the significance of this overhead, but
still...)
With the next C++ standard there might be one reason to prefer
std::vector in some cases, especially if the array is very large:
std::vector will automatically support move semantics, which C-style
arrays can't do.
What I believe Stroustrup was talking about was that in
situations where you would need the second type of array, you
should definitely use std::vector instead, because it's much
safer.
I suspect that Stroustrup was talking about all use.
But having a std::vector with three elements as a member variable is
going to be significantly less efficient than having just an array of
three elements, no matter what you do and what tricks the compiler can
come up with. It would be odd to recommend using std::vector in this
kind of case as well.
And when I say "significant" I don't mean "maybe 1% slower". More like
"at least 10 times slower" with many operations (such as creation,
copying, etc).
However, if you have such a small, fixed-size array as the
member of a class, then using a static array is definitely
more efficient than using a dynamic array (which includes
using std::vector).
I think you meant C style array, and not "static array".
The terminology is rather confusing. An array allocated dynamically at
the end of a pointer could also be thought as a "C style array" (in
contrast to std::vector)...
I used "static" as opposed to "dynamic" (ie. allocated dynamically
with new), rather than meaning "static member".
What *is* the opposite of "dynamically allocated", if it's not
"statically allocated" (ie. "static" for short)?