In environment that has many custom heap allocators, is it generally required that address of original void*
need to be cached within the custom smart pointer?
Example
To identify the allocator (Allo
) of a certain memory block content
later :-
When the block is allocated, I think it is necessary to store a hacky infomation (meta-data
and Allo*
) near it.
When I want to deallocated a void*
, I can minus the void*
pointer to find the Allo*
e.g.
template<class T>class StrongPointer{
public: void* content;
public: ~StrongPointer(){
Allo* allo=static_cast<Allo*>((void*)(static_cast<char*>(content)-4));
//^ 32-bit system
allo->deallocate(content);
}
public: void get(){ return static_cast<T*>(content); }
}
It should work.
However, this thing will break when I want it to support casting StrongPointer<Derived>
-> StrongPointer<Base2>
.
(According to C++ virtual table layout of MI(multiple inheritance))
class Base1{/*some fields */};
class Base2{/*some fields */};
class Derived : public Base1,public Base2{};
For example, the result of casting StrongPointer<Derived>
to StrongPointer<Base2>
will has StrongPointer<Base2>::content
that doesn't directly next-to the location of Allo*
anymore.
template<class T1,class T2> StrongPointer<T2> cast(StrongPointer<T1>&& t1){
StrongPointer<T2> r;
r.content=static_cast<T2*>(t1.get());
//^ location change, so "content-(4 bytes)" doesn't point to Allo* anymore
return r;
}
Question
In my opinion, there are some workarounds:-
- store
Allo*
inside every strong pointer. OR - store offset which +/- in every casting OR
- store
Allo* + 1
which reflect the real address of allocated content
It all boils down to :-
Do I really have to store another variable inside Strong_Pointer<T>
?