Hello. I'm having a bit of trouble with the sizeof() operator in C++. I'm working on a garbage collection system with some smart pointer objects. So far, they've worked beautifully, but I'm having trouble with the sizeof() operator.
The smart pointer that does the garbage collection is Handle<typename T, unsigned Size>. Handle supports arrays, which is why it has a Size template parameter. This enables some neat bounds checking features, including assignments between Handles that may lead to an array whose max index will refer to unallocated/unreserved memory.
However, to get this feature
fully functional,
I need a means of using the sizeof() operator polymorphically. The problem is polymorphic classes. Let's say we have two simple classes called A and B like this:
class A
{
public:
A(): _myInt(0) {}
virtual ~A() {}
private:
int _myInt;
};
class B : public A
{
public:
B(): _myFloat(0.0f) {}
virtual ~B() {}
private:
float _myFloat;
};
Simple enough. As I said before, with my Handle class, I can do something like this:
...
Handle<A, 10> hva1 = new A[10];
Handle<A, 3> hva2 = &hva1[2]; // Safe.
Handle<A, 6> hva3 = &hva1[8]; // Error! Throws exception! Bounds overlap!
...
The last line there will throw an exception because hva3 is declared an array of size 6, but it refers to an array of As that is of size 2 (hva1[8] and hva1[9]). Removing that line will get rid of the exception and run just fine, letting the collector do the cleanup work.
However, this will not work properly:
...
Handle<A, 100> hvb1 = new B[10]; // No complaint; Bs are As.
Handle<A, 20> hvb2 = &hvb1[79]; // This should work, but depending on the nature of A and B, it may throw an exception!
...
I haven't tested this specific example, but I know that depending on how A and B are defined, the second line may or may not throw an exception, which means that the behavior is essentially undefined and dangerous. I know this sort of assignment into arrays is strange, but I'm trying to make Handle as flexible as possible.
So, after all of that rambling, my question is...
is there a way to use sizeof() polymorphically? If I have a pointer of type A that points to a B, can I somehow get the size of B when I pass that (dereferenced) pointer to sizeof()?
Thanks! I appreciate any help.