Like, if you had a memory pool, could you somehow incorporate smart pointers into all of that? I feel like you can and should be able to but for some reason, I'm not sure.
Like, if you had a memory pool, could you somehow incorporate smart pointers into all of that? I feel like you can and should be able to but for some reason, I'm not sure.
For some containers, maybe. But at that level, I think the container often requires fine-grained control over the lifetime of the elements, so a smart pointer might just get in the way, whereas an allocator provides a better abstraction.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
It depends what you mean by incorporating. I'm only guessing that you mean something like std::set<std::shared_ptr<std::string>> which holds preallocated container values.
I can point out that the main problem with allocators is that they must be type-agnostic, whereas smart pointers are type-specific. The fact that they are templates is very misleading - this is wrong, allocators are not truly generic. For example, when you pass std::allocator<T> to some container<T> (e.g.: list<T>), there is no guarantee that container will use that implementation of allocator to allocate elements of T directly. Allocators can be rebound to any other type U by the container. It means that every implementation of an allocator must actually be able to allocate all possible types. For example, to avoid memory fragmentation, a list<T> container instead of allocating T directly, may instead choose to allocate a wrapper structure (node) containing: value (of type T), pointer to previous node, and pointer to next node. You cannot handle that scenario in a set, because the wrapper (node) type depends on specific implementation and you have no information of how it looks like (it might even not exist at all).
Also, std::vector is kind of a special container: it is required to store its elements in a contiguous chunk of memory, so using std::shared_ptrs for individual elements is out of question (it would no longer be a contiguous allocator).
This is true that allocators are mostly used to find uninitialized storage, however, allocators can optionally provide a construct() and destroy() member functions, so in theory you could make it no-operations and prevent construction and destruction of elements altogether (I doubt it would work due to other issues, though).
Last edited by kmdv; 03-18-2016 at 02:40 AM.
Huh, that was an interesting read, kmdv.
But my sentiments were the same, laser. I'll keep thinking about it in the back of my mind though. Might someday become relevant.