What is the use of creating objects on the free store?-Collection of common programming errors
Important reason is how stack works. It has only push and pop operations. You can not release something in stack, before you have released everything pushed after it. Or to put it another way, if something is released from stack, such as function call’s stack frame when function returns, then all memory above it in stack will be released also (and you’d better make sure it gets destructed properly, see below).
Programs generally need to store data independent of stack. There are two ways: allocate memory at compile time, as static data, or allocate it in free store, also called heap.
It would certainly be possible to have several stacks, and in fact this is commonly done too, when convenient and useful. But it is done by using a stack container variable, with type such as std::stack
, then using that as extra stack for data only. Common processor architectures have just one “native” stack per process/thread, and that is used for function calls and stack variables, these extra stacks are always separate and created by the program code, just plain data structures same as lists, maps etc.
About code in your question, a point to make is that in modern C++ a naked new
is generally frowned upon. You should use a RAII mechansim such as a smart pointer:
void fun()
{
auto a = std::unique_ptr{ new A }; // C++11 syntax
// object is automatically destroyed when a goes out of scope, no leak
// note: heap should be used like this only if there's a reason, including:
// - A is big, and might conceivably overflow the stack
// - ownership of object may get moved and outlive the unique_ptr
}
And your specific question “The object created exists on the free store and cannot be used by the main() function. The why should the objects be created on the free store.“, well, in the question code, it should not be created in free store, there’s no reason. It should be just plain automatic variable which gets automatically destructed when it goes out of scope.