3 ms·
std::vector does indeed have at least one pointer member (otherwise you couldn't have a std::vector with automatic storage duration because the size would be un
by tines 10y ago
std::vector does indeed have at least one pointer member (otherwise you couldn't have a std::vector with automatic storage duration because the size would be unknowable) so there is some indirection. Maybe you're thinking of std::array?
- kr7 10y agokzrdude is referring to the allocation of the Array struct on the heap. It should be something like this instead: Array array_create(size_t size, size_t sizeof_data) { Array result; result.size = size; result.capacity = size; if(size) { result.data = malloc(size * sizeof_data); } else { result.data = NULL; } return result; }
- oconnor663 10y agoI think kzrdude is actually referring to the void* pointers that the individual elements of the array live behind. Each of those requires an allocation to insert them, and an extra pointer traversal to read them. In C++ they would live side by side instead, as in regular C arrays. In C you'd need the struct to be redefined for each element type (maybe with another macro) if you wanted the same efficiency.
- kr7 10y agoI'm not seeing that? In ARRAY_PUSH_BACK, it just inserts the element directly into the buffer, provided there is enough capacity. There is no separate allocation for an element. You don't need to redefine the struct for each element type, since the macro casts 'data' (type void *) to whatever the array's type is.
- oconnor663 10y agoYou're totally right, I don't know what I was reading >.<
- kzrdude 10y agoYes exactly.
- kzrdude 10y agoThis C code is more like `std::unique_ptr<std::vector<T>>`, so now you might see where the extra indirection is located.