I have noticed that many libraries (e.g. Box2D
, Bullet
) use user-pointer e.g. void*
.
However, in some cases, I believe using value is faster/better.
- avoid heap allocation / better memory locality
- don't need to
delete
it manually, or use smart pointer - sometimes, it just simply looks better
- when user don't set value of userData (leave as default), the program will not crash
What are disadvantage using value?
More Solid Example
I have a performance-critical complex database ComplexDB
that has callback.
Whenever it add/remove new elements by any means, it will callback.
template<class T,class Callback> class ComplexDB{
Callback call; //<-- will be Callback* in pointer-version
void addElement(const T& t){
Callback::callbackAdd(call,t); //<-- callback
}
// other complex functions that may call "addElement()"
};
class MyCallback{
int custom=5;
public: static void callbackAdd(const MyCallback& c,int a){
int cus=c.custom;
//^ It is cheaper than pointer-version,
// because c's address has memory-locality near "ComplexDB".
}
//other function e.g. callbackRemove(), and a few other callbacks
}
It works good.
Nonetheless, I am very new to C++, so I am afraid that I am violating some C++ holy tradition, and I will be punished e.g. cause maintainability problem / broken design.
I have doubted about this for a week, but feel very reluctant to ask it.
If this question should be improved in some ways, please comment. Thank.
Here is the most related question, but it focus on approaches that require v-table look-up or std::function
that I can't afford.
Edit: The ComplexDB
expects that a callback class to contain specific 3-5 functions.
(e.g. callbackAdd,callbackRemove,...)
Thus, I think it is suitable to pack it as only 1 template-argument slot.