4 ms·
What's the equivalent pattern in C++ to do this then? Specifically a contiguously allocated but variable length struct. I was thinking you can use template:
by rawnlq 10y ago
What's the equivalent pattern in C++ to do this then? Specifically a contiguously allocated but variable length struct. I was thinking you can use template:
template <int N>
struct ion_system_heap {
struct ion_heap heap;
struct ion_page_pool *pools[N];
};
But that is not quite the same thing since ion_system_heap<10> and ion_system_heap<20> won't be the same type and makes it super hard to use. And a whole bunch of other problems like not knowing how many pages you want to allocate at compile time.
Yes you can just use a vector for "pools" but that allocates it on the heap instead of in the struct.
- CyberDildonics 10y agoTwo types must be the same size, if they weren't how would sizeof() work, or vector<> for that matter.
- rawnlq 10y agoThis problem is also on stackoverflow: http://stackoverflow.com/a/1391001 http://stackoverflow.com/a/1391001. It solved it by wrapping with a superclass that you downcast from. You won't be able to work with them by value due to object slicing but you can still have a vector of pointers: vector<Panda_without_bamboo*> pandas; I am not sure how to do the downcasting though. Assuming the classes look like this: public Panda_without_bamboo { int bambooCount; } template<std::size_t N> class Panda_with_bamboo : public Panda_without_bamboo { int a; int b; Bamboo bamboo[N]; } You can't really do: static_cast<Panda<pandas[0].bambooCount>*>(pandas[0]) So it does seem like using flexible array members (first answer in that stackoverflow and the topic discussed in this submission) is a cleaner solution if you need contiguous allocation: http://www.codeatcpp.com/2007/10/dynamic-array-template.html http://www.codeatcpp.com/2007/10/dynamic-array-template.html
- CyberDildonics 10y agoOf course you can create a vector of pointers and do whatever you want. If you need contiguous memory though this is likely a terrible way to go about it since you are not only having to dereference pointers that could go anywhere, but each one will mean a separate heap allocation which will be slow for small objects and not scale with concurrency.