I know this question has been asked before but I could use some clarification. Here is a simple example I was trying to understand:
string s1;
string *s2 = new string();
What I know:
- s1 will be created on the stack
- s2 will be created on the heap
- The stack is faster
- s2 must be manually deleted
- In general - create on stack unless you have to create on the heap.
What I am confused about:
- When would you ever have to use the heap? - A common advantage I've read is the object will still be available after you exit the scope of the function it is created in. Why would this ever be desirable? Couldn't just just create on the stack and then pass by reference to use that object outside of your current function? An example would be very helpful.
- I am aware that the stack has a limited amount of memory so in the example above if I were to store a huge string into both s1 and s2, is there a point where s1 would overflow (would this cause a stack overflow?) while s2 would retain all the input? If such a point does exist is this dependent on the machine and is there a way to find out the max s1 could store before such a problem occurs?