5 ms·
> For example, std::vector in C++ is a value type but the array storage is heap-allocated. This isn't correct. Firstly, C++ doesn't have value or reference typ
by hermitdev 8y ago
> For example, std::vector in C++ is a value type but the array storage is heap-allocated.
This isn't correct. Firstly, C++ doesn't have value or reference types. Where any object is stored depends purely on how it is allocated. Either in the free store (dynamic) or automatic storage (the stack).
std::vector has a constant object size - typically the size of 3 pointers (but that depends on the implementation - the standard doesn't specify): the start of the memory (dynamically allocated for storage), end/capacity (typically either another pointer or a size_t of the current capacity), and back (typically either a pointer just past the last element used or a size_t + 1 of current size). It's storage is dynamically allocated, though, and for a std::vector<T> will have dynamically allocated sizeof(T) * capacity bytes (maybe more due to alignment issues).
std::array is constexpr safe and does not (directly) dynamically allocate memory - size has to be known at compile time (hence it's a template argument).
For instance, on my compiler (GCC 4.8.4), for this example program:
#include <iostream>
#include <vector>
#include <array>
int main()
{
std::vector<int> v_ten(0, 10);
std::vector<int> v_twenty(0, 20);
std::array<int, 10> a_ten{0};
std::array<int, 20> a_twenty{0};
std::cout << "sizeof(v_ten): " << sizeof(v_ten) << std::endl;
std::cout << "sizeof(v_twenty): " << sizeof(v_twenty) << std::endl;
std::cout << "sizeof(a_ten): " << sizeof(a_ten) << std::endl;
std::cout << "sizeof(a_twenty): " << sizeof(a_twenty) << std::endl;
return 0;
}
produces this output:
sizeof(v_ten): 24
sizeof(v_twenty): 24
sizeof(a_ten): 40
sizeof(a_twenty): 80
edit: added comment about alignment.
- dbaupp 8y agoThe parent is correct. std::vector is a value type in the sense that everyone else is talking about... All types in C++ are, as their members are not inherently stored on the heap. C++ (and C, and Rust) has types that behave like what other languages call value types, even if there is not any other sort of type. The mention of array in the parent was referring to the dynamic storage of a vector, not std::array.