Reputation: 1010
According to the reference a simple std::vector<T> vec;
creates an emtpy container (default constructor). Does this guarantee that there is no dynamic memory allocation?
Or may an implementation chose to reserve some memory?
I known that, for this empty constructor, there is no construction of the type T
since C++11.
However, I wonder, if there is also a guarantee that nothing is allocated on heap. I.e. that the above line is just a few nullptr
on stack/member.
I tested it with vc140, where it is indeed free of dynamic allocations.
Upvotes: 27
Views: 3678
Reputation: 41
There is no guarantee.
A counter example that I just hit (and which led me to this post) is MSVC2017's STL implementation, if _ITERATOR_DEBUG_LEVEL > 0.
Upvotes: 4
Reputation: 275740
std library is part of the C++ language.
Almost any call to any std library class or function could do pathological and insane things. But the same is true of int x=7;
-- the standard is not written to defend against frankly hostile C++ implementations, which includes the std library.
That being said, the zero argument constructor to std vector is noexcept. This means it is intended to not allocate. A hostile implementation is free to allocate, catch any errors, and proceed regardless of if the allocation succeeded. A hostile implementation is also free to count to 47 trillion, run some FFT on random data, spin up a neural network and train it against Shakespeare, compose some sonnets, then proceed as if nothing happened. The standard has nothing to say on the inobservable poetry composition of any operation in C++; so long as the action has no observable (within the abstract machine) side effects, the standard has no opinion.
In practice there is no reason for std::vector<T>()
to allocate, and no later operation on it can assume it allocated. I could see an instrumented build allocating some lifetime tracking token to enforce iterator invalidation errors, but that would only be enabled in debug with extra flags (e.g. -DCMP_JUN17
).
Worry more about poetry than a call to new.
Upvotes: 31
Reputation: 238401
Does this guarantee that there is no dynamic memory allocation?
No. It is however quite typical that an implementation doesn't allocate memory. I haven't seen a standard library implementation that does.
Or may an implementation chose to reserve some memory?
It may, but that's atypical.
I known that, for this empty constructor, there is no construction of the type
T
since C++11
Also prior to C++11.
Upvotes: 29