Simple example:
template <class P> class MyT
{
struct Item
{
public:
Item() {}
P *pData;
Item *next;
};
Item *head;
public:
...adding etc..
P* operator [](int index)
{
See question below:
}
};
Can I somehow make sure that the ‘Item’s are allocated in such a way that I can calculate the offset as follows: (@Steve:) Maybe not so clear here; what I need is a quick & easy way to get to the item without iterating through 10000 next’s.
Item *pi = head + (sizeof(Item) * (index - 1));
A (clearer?) explanation of what I mean
Depends what you mean by “etc”, in “adding, etc”.
If “etc” includes, “removing”, then you have the obvious problem that if you remove something in the middle of your list, then to maintain the indexing you have to shift everything after it downwards, which means updating all the
nextpointers.I think perhaps you have simplified your example too far. If you require contiguous storage, use a vector (either of
P, or ofItemif there’s something useful inItemthat you’ve removed). If you have contiguous storage, then there’s no benefit in having anextpointer, since you could just calculate it inItem, by adding 1 tothis(then checking a bound to make sure you haven’t reached the end).If you absolutely need the public
nextpointer field, because it’s part of some interface you’re implementing that you can’t change, then you could update it in the copy constructor andoperator=forItem, and the interface had better forbid clients from writing to it.There’s no way to tell the memory allocator to allocate contiguous storage for separate allocations, if that’s what you’re asking. How would that even work? What if when you come to allocate, the “next” address is already occupied? What if the allocator imposes some overhead, for its own control structures (as almost all general-purpose allocators do), so that allocating an
Itemrequires more thansizeof(Item)bytes? You can get the behaviour you want for a while with a fixed-size allocator, but eventually it needs a new block, or you delete something, and the relationship no longer holds.