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 T>
class Base
{
protected:
T x;
public:
Base() {}
Base(T _x) : x(_x){}
virtual bool func() = 0;
};
Now, as for the derived class:
template<class T>
class Derived : public Base<T>
{
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<int>* d = new Derived<int>[size];
for (int i = 0; i < size; i++)
{
d[i] = Derived<int>(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<int>** d = new Base<int>*[size];
for (int i = 0; i < size; i++)
{
d[i] = new Derived<int>(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<Base<int>*>
and boost::ptr_vector<Base<int>>
.