C++: Is it ever absolutely necessary to allocate memory manually?
c++, memory, memory-management
Solution
The stack is of a limited size, some things just won't fit in it reliably. Dynamically allocated memory also has the dynamic nature to them, where sometimes you're not sure how many objects or elements in an array you will require until some moment in time of the execution of the program.
Check out this question, it does a great job of describing possible use cases for each:
Heap allocations (dynamically allocated memory) is useful when you want to be more flexible than the above. Frequently, a function gets called to respond to an event (the user clicks the "create box" button). The proper response may require allocating a new object (a new Box object) that should stick around long after the function is exited, so it can't be on the stack. But you don't know how many boxes you would want at the start of the program, so it can't be a static.
To reflect your edit: Indeed it's not really required, or rather, it's typically abstracted away as is the case with `vector` and `string`. You have various containers like `vector` which handle that for you. When you design your own classes, you're encouraged to employ the technique of Resource Allocation is Initialization (RAII) which abstracts away the typical manual memory management. In fact, in certain cases, especially when dealing with C code, you're encouraged to manage that memory either in a C++ class wrapper employing RAII or with a C++ smart pointer such as those introduced in C++11: `shared_ptr` and `unique_ptr` (which themselves employ RAII).
Problem
I'm relatively new to some of the more advanced aspects of C++ programming and I'm having some trouble understanding if it is ever truly necessary to allocate memory in C++ (whether it be through malloc, new, etc.). For example in C, I understand you need to allocate memory to have a dynamically sized array or other tasks. In C++, it seems to me that's not the case, you can just use a std::vector, std::string, or other built in methods which are already dynamically sized by design. I also understand that accessing allocated memory is slower vs the stack. So given that, are there times when you must allocate memory in C++, and if so, what is an example of one of those times? This of course does not include times when your C++ code must interact with a C program. Let's assume the program is written purely in C++. EDIT: To try to alleviate confusion, I understand that vectors and other structures are allocating their own memory, but that's something that happens behind the scenes and does not require the programmer to use new, malloc, etc. and it is cleaned up automatically. So what I'm really wondering is, is it ever necessary to perform memory management manually in C++