I just started using STL, say I have a rabbit class, now I'm creating a rabbit army...
#include <vector>
vector<rabbit> rabbitArmy (numOfRabbits,rabbit());
//Q1: these rabbits are on the heap right?
rabbit* rabbitOnHeap = new rabbit();
//Q2: rabbitOnHeap is on the heap right?
rabbit rabbitOnStack;
//Q3: this rabbit is on the stack right?
rabbitArmy.push_back(rabbitOnStack);
//Q4: rabbitOnStack will remain stored on the stack?
//And it will be deleted automatically, though it's put in the rabbitArmy now?
Q4 is the one I'm most concerned with, should I always use new keyword to add rabbit to my army?
Q5: Is there better way to add rabbits to the army than:
rabbitArmy.push_back(*rabbitOnHeap);
std::allocator<rabbit>
, which uses new
. For what it's worth, that's usually called the "free store" rather than the heap1.new
to allocate items you're going to put in a standard collection. Since the item in the array will be a copy of what you pass, you don't normally need to use new
to allocate it.For example:
for (i=0; i<10; i++)
rabbitArmy.push_back(rabbit());
This creates 10 temporary rabbit
objects (the rabbit()
part), adds a copy of each to the rabbitArmy. Then each of the temporaries is destroyed, but the copies of them in the rabbitArmy remain.
calloc
, malloc
, realloc
, and free
. What new
and delete
manage is the free store. A new expression, in turn, obtains memory from an operator new
(either global or inside a class). operator new
and operator delete
are specified so they could be almost a direct pass-through to malloc
and free
respectively, but even when that's the case the heap and free store are normally thought of separately.