C++ array of derived class vs array of pointers of base class to derived objects – why is amount of memory allocated so much different?-Collection of common programming errors
I need some clarification on an issue I don’t quite understand. Using the two scenarios that follow, I would have thought that the amount of memory allocated would roughly be the same. However, scenario 2 gives me a bad_alloc exception after a while and appears to be chewing up memory like crazy (using Window’s Task Manager as a proxy for the amount of memory allocated to the process). The following is compiled on Windows 32bit using MSVC10.
Say I have following base class:
template
class Base
{
protected:
T x;
public:
Base() {}
Base(T _x) : x(_x){}
virtual bool func() = 0;
};
Now, as for the derived class:
template
class Derived : public Base
{
public:
Derived() {}
Derived(T _x) : Base(_x){}
bool func() { return true; };
};
Now consider two cases. First, allocate a dynamic array of the Derived class and fill it up with Derived objects, ie:
int main()
{
int size = SOME_LARGE_NUMBER;
Derived* d = new Derived[size];
for (int i = 0; i < size; i++)
{
d[i] = Derived(i);
}
// delete here
}
Second, allocate a dynamic array of pointers of the Base class and have them point to actual instances of the Derived class, ie:
int main()
{
int size = SOME_LARGE_NUMBER;
Base** d = new Base*[size];
for (int i = 0; i < size; i++)
{
d[i] = new Derived(i);
}
// delete here
}
I set SOME_LARGE_NUMBER in either scenario to 40,000,000. In the first scenario, the program completes fine – in the second one I get a bad_alloc exception. I am wondering whether this is expected behaviour or whether I am overlooking something here? If so, what’s a better way of doing this? Note that I get the same problem using vector and boost::ptr_vector.