Skip to main content
gamedev.net
🔒 Locked

Function Pointer Problem

Started by KemiKal 1 reply 350+ views
Original Post
KemiKal
KemiKal
Hi, im currently working on some container classes (just for learning purposes) and have come across a problem. I want to allow people to pass custom memory allocators to the class when they are constructed but im not sure of the best way to do this. My first thoughts were to pass a function to a constructor and then store it as a member variable but this was where problems arose. Firstly the function will need access to the protected member variables of the class, im guessing I could just pass the *this pointer to it but then the protected members would be accessible to everyone. Secondly I have a default memory alloction function in the class that is used if no allocator is supplied. The problem with this is that any function passed in wont be of the _this calling convention and therefore wont be accepted. Is there any simple ways around this problem? I guess I could just have the allocator as a virtual function and have the user inherit from it but I wanted to already inherit from my base containers to create more advanced ones. This would just leave me with several layers of inheritance making things more complicated than they should be. So does anyone have any suggestions? How does the stl take care of this problem? Thanks for any input ^_^
SiCrane
SiCrane
The STL uses allocator classes that are passed to the container class as a template argument that defaults, for a container of T, to std::allocator. The allocator class has allocate and deallocate functions that the container class calls for allocations and deallocations. The container class often inherits privately from the allocator class or stores a member variable of the allocator class type.
KemiKal
KemiKal
Ah thanks for the quick reply. I guess it does make sense to remove the variables concerned with memory allocation to their own class. Ill have a deeper look at the STL I think. Thanks again, back to coding!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.