3
#include <iostream>
#include <string>
using namespace std;
int main () {
  string str = "Hello";
  str = "Hello World";
  cout<<str<<endl;
}

How is the memory handled by the string?

Hemant
  • 225
  • 4
  • 17
  • 1
    `std::string` will automatically copy the string over into its own memory. – Mateen Ulhaq Jan 08 '17 at 09:16
  • 6
    `std::string` will *possibly clear* up its old contents and copy the new string into it. (It will expand the memory storage used for storing the strings if need be) You should get some [good C++ books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and read them. – WhiZTiM Jan 08 '17 at 09:16
  • @WhiZTiM how will it do so without changing its address. – Hemant Jan 08 '17 at 09:22
  • 2
    @Espionage: The buffer address, e.g. `&s[0]`, changes when the `string` instance reallocates its internal buffer. – Cheers and hth. - Alf Jan 08 '17 at 09:23
  • @Cheersandhth.-Alf Thanks I think I understand it, but there is still one more thing I am not sure of, what changes will be made in the memory stack of the `main ()` function to make this happen. – Hemant Jan 08 '17 at 09:33
  • @MateenUlhaq thanks for the reply. – Hemant Jan 08 '17 at 10:14

1 Answers1

7

Re:

How is the memory handled by the string?

Automagically.

That means, among other things, that there's no way to give a std::string, an externally created buffer. So it's a bit inefficient. On the bright side, the swap requirements for std::string (as opposed to std::vector) means that it can use the small buffer optimization, where short strings are stored without dynamic allocation, which helps to improve efficiency.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • Can you please give us a view of the memory stack. – Hemant Jan 08 '17 at 09:46
  • 1
    @Espionage: I think by "memory stack" you mean "memory layout". There's not much to it. With the small buffer optimization the (very short) string is typically stored directly in the `std::string` instance. And otherwise that instance holds a pointer to a dynamically allocated buffer elsewhere. – Cheers and hth. - Alf Jan 08 '17 at 09:59
  • What could be the length of a very short strings? – Hemant Jan 08 '17 at 10:08
  • 1
    As much as fits in one or two pointer values' worth. For a 32-bit compiler that's not much, like 7 characters or so. For a 64-bit compiler it might be twice that. – Cheers and hth. - Alf Jan 08 '17 at 10:14