2

If I assign a new value too previously declared string using operator= , is it freed automatically or I have to free it manually?


std::string s("value_old");
s = "value_new";

what happens with "value_old" where I can find or where are you always watching to find answer to similar questions? Thanks in advance.

egrunin
  • 24,038
  • 8
  • 48
  • 92
Yevhen
  • 1,839
  • 2
  • 14
  • 25

5 Answers5

8

std::string handles it's own memory, so when you use s = "value_new", the string "value_old" is sent to oblivion.

badgerr
  • 7,584
  • 2
  • 26
  • 42
5

Yes, it is freed automatically.

I suggest cplusplus.com for a handy online reference to STL.

egrunin
  • 24,038
  • 8
  • 48
  • 92
1

The old value is freed and s becomes new_value.

From Source code std::string, The old value is erased (from erase() method) and new value is inserted and a reference string is returned. See assign() method.

Buhake Sindi
  • 85,564
  • 27
  • 164
  • 223
1

Generally: If you're using std::string you don't need to worry. It will take care of that.

In your concrete case: Very likely your std::string implementation will recycle the memory it had for "string_old", re-using it for "string_new".

sbi
  • 212,637
  • 45
  • 247
  • 432
1

The std::string manages the actual data and is responsible for memory management.

Where I can find or where are you always watching to find answer to similar questions?

For such questions, I would recommend a simple C++ book. A list is available on this post, but I think "The C++ Language" (Bjarne Stroustrup) would be a good choice to start with.

Community
  • 1
  • 1
icecrime
  • 71,079
  • 13
  • 98
  • 110