Yannick said:
Of course. Valgrind should report it.
hmm, given that valgrind only has the compile code, not the source,
then something must be different as a result on what it does. But
regardless, it is nice that valgrind spots and report it.
Practically however: I do not remember the last time I used new[]. I
honestly never use it. In the huge huge huge majority of cases,
"std::vector<int>(n)" will do better than "new int[n]".
I find "new" useful, albeit rarely, but "new[]", virtually never.
Have you ever compared the performance of std::vector<int>(n) vs. new
int[n] (in a release build, but without optimization?)
Why would I not want to let the compiler optimize the code?
This is a typical C hand coder way of opting out: "C++ is slow. Look I
compile with debugs and no optimization and std::vector::at() is 10x
slower than accessing a malloc'ed array and std::vector:
ush_back()
is 50x slower than memcpy".
My results are somewhere factor 5 on VC8 (VS2005) in favor of new[].
Try again with optimization on. You will probably find:
std::vector<int>(n) is a bit slower than new int[n] but not much
std::vector<int>(n) is about the same speed as
int * p = new int[n]; memset(p,0, n * sizeof(int));
it is hard to measure the speed difference between: accessing data i a
std::vector using operator[] and in a new'ed array using [].
It is a bit slower to access data using vector::at() but if you turn
on optimisation, it might be hard to notice.
try for example Stepanov containers benchmark:
http://www.stepanovpapers.com/container_benchmark.cpp
On my machine, the performance of vectors is typically better than
that of arrays once I turn on optimization. With optimization totally
off, "vectors with iterator" is half the speed as array but with
optimization on, surprisingly, "vector with iterator" takes an
insignificant lead with -O2 and array or "vector with pointers" are a
bit faster with -O3
Most of the time, the performance difference will not matter while the
safety (bugs and buffer overflow) are likely to matter most of the
time.
I agree though - I do not use new[] except in the classes that hide it
from me.
Also - technically the (2003) std does not guarantee that the memory of
std::vector is allocated contiguously, right?
Wrong, it is guaranteed.
std:string are not guaranteed contiguous yet although I have yet to
see one that isn't but vector is guaranteed.
See:
http://www.parashift.com/c++-faq-lite/containers.html#faq-34.3
Yannick