G
Gonçalo Rodrigues
Hi all,
I have a template class (call it Object) whose instances have a
variable size part - an array of of T objects. But this variable size
part is fixed at creation time so instead of allocating two blocks
(one for the object and one for the variable-sized part) one can
allocate a single block via a placement new operator like
template<typename T>
void* Object<T>:perator new(std::size_t sz, std::size_t number) {
return new char[sz + number*sizeof(T)];
}
Creation of Object's goes through factory static methods so these
implementation details are hidden from the client.
I have the following function to get the pointer to the variable part
template<typename T>
T* Object<T>::getPtr() const {
return (T*)(this + 1);
}
Now the problem is the following: suppose (fixing the parameter type
T) that I derive from Object<T> and also assume that the derived class
adds some instance data. Then am I right in concluding that the above
getPtr returns the wrong answer? And if I am right, how to make sure
that getPtr returns the right pointer for derived classes?
TIA, with my best regards,
G. Rodrigues
I have a template class (call it Object) whose instances have a
variable size part - an array of of T objects. But this variable size
part is fixed at creation time so instead of allocating two blocks
(one for the object and one for the variable-sized part) one can
allocate a single block via a placement new operator like
template<typename T>
void* Object<T>:perator new(std::size_t sz, std::size_t number) {
return new char[sz + number*sizeof(T)];
}
Creation of Object's goes through factory static methods so these
implementation details are hidden from the client.
I have the following function to get the pointer to the variable part
template<typename T>
T* Object<T>::getPtr() const {
return (T*)(this + 1);
}
Now the problem is the following: suppose (fixing the parameter type
T) that I derive from Object<T> and also assume that the derived class
adds some instance data. Then am I right in concluding that the above
getPtr returns the wrong answer? And if I am right, how to make sure
that getPtr returns the right pointer for derived classes?
TIA, with my best regards,
G. Rodrigues