0

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:

  1. s1 will be created on the stack
  2. s2 will be created on the heap
  3. The stack is faster
  4. s2 must be manually deleted
  5. In general - create on stack unless you have to create on the heap.

What I am confused about:

  1. 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.
  2. 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?
trincot
  • 317,000
  • 35
  • 244
  • 286
Eric S
  • 1,001
  • 10
  • 14
  • related: http://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable – Borgleader Aug 31 '16 at 19:43
  • 3
    The contents of a `std::string` are not stored on the stack, so the length of the string doesn't matter. Only the metadata used by the `string` class is on the stack. – Barmar Aug 31 '16 at 19:44
  • ***s2 must be manually deleted*** If you need to create an object on the heap you can use a smart pointer and never use new / delete. However this is not a case where I would do this. Remember the buffer for `std::string` will be dynamically allocated. – drescherjm Aug 31 '16 at 19:44
  • 1
    **Couldn't just just create on the stack and then pass by reference to use that object outside of your current function?** When the function returns, all objects in its stack frame are destroyed, and references to them are invalid. – Barmar Aug 31 '16 at 19:45

0 Answers0