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?
4
  • related: stackoverflow.com/questions/4643713/… Commented Aug 31, 2016 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. Commented Aug 31, 2016 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. Commented Aug 31, 2016 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. Commented Aug 31, 2016 at 19:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.