Reputation: 638
Imagine a structure
struct A {
int i;
int arr[1000];
};
std::vector<A> vec;
I cannot find an answer to know if the array "arr" in my structure "A" will take up space on the stack or not at all. I these although the vector will allocate an array of "A" which will be on the heap and will not impact my stack but will my "arr" array impact my stack?
std::vector <A> vec1 (1000000);
std::vector<std::unique_ptr<A>> vec2 (1000000);
Will vec1 "destroy" my stack and better to use vec2?
Edit for the comment.
Why can vec1 allocate more elements than vec2?
#include <iostream>
#include <vector>
#include <memory>
struct A {
int i;
int arr[1000];
};
int main() {
std::vector<std::unique_ptr<A>> vec1;
std::vector<A> vec2;
std::cout << vec1.max_size() << '\n' << vec2.max_size() << '\n';
}
Upvotes: 1
Views: 376
Reputation: 14688
std::vector
is one of AllocatorAwareContainers and default allocator use dynamic allocation (often called heap allocation, which is true for systems with heap-like memory model).
When using those two
std::vector<std::unique_ptr<A>> vec1;
std::vector<A> vec2;
both have own advantages and disadvantages. The vec1
offers arguably better time of resizing container itself because unique_ptr is quite small. vec2
offers instances of A with adjacent storage but resize time would be higher because of move operation used on each element. vec1
allocates only storage for pointers and not for the object itselves, by reaching that number you likely won't have memory left to create instances of A
.
For lesser automatic storage (stack) footprint when using vec2 you might want to avoid creation of A
temporary at all and use emplace_XXX
methods to create instances of A right in vector's storage.
Upvotes: 3