I would like to use different instances of an STL custom allocator class to manage different memory spaces, and then be able to specify an allocator instance to an STL container such that each container only draws from its assigned memory space. But I don't see how I can do that. I see how I can pass an allocator type into the template parameters of an STL container, but I want something akin to passing an allocator instance into the constructor of an STL container. Is there a way to do this in STL?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
Unfortunately STL allocators cannot have state (or at least have to be very careful how that state is used) - each instance of a particular allocator type must be equivalent for STL containers to work effectively with them. I don't recall the details right now, but I know that Scott Meyers discusses this problem at length in "Effective STL", Item 10: Be aware of allocator conventions and restrictions.
However, you can have templated allocators that are very similar with the differences between the allocators being encapsulated in the allocator type and use different 'instantiations' of the allocator template (each template 'instantiation' is a different type). Again, my recollection is that Meyers discusses this pretty clearly.
For example see this paragraph from an article by Anthony Aue, "Improving Performance with Custom Pool Allocators for STL":
See also Stephan T. Lavavej's discussion in this newsgroup thread.
I'll update later tonight if someone else doesn't give the details in the meantime.
The STL containers allow you to pass the allocator in as an argument to the constructor.
For example here are the appropriate constructors for vector:
By default, they just use a default constructed allocator.
Perhaps you could code a set of allocator types which contains a static pointing to seperate memory spaces.
Then, when the STL container constructs its allocator, the allocator uses the memory spaceassigned to that allocator.
For simplicity, assume you want to use two memory spaces. Create two allocator types, one for each space. Pass the allocator type to the STL container constructors as required.