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,650
  • 8
  • 50
  • 93
Yevhen
  • 1,897
  • 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,802
  • 2
  • 28
  • 43
5

Yes, it is freed automatically.

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

egrunin
  • 24,650
  • 8
  • 50
  • 93
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
  • 87,898
  • 29
  • 167
  • 228
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
  • 219,715
  • 46
  • 258
  • 445
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
  • 74,451
  • 13
  • 99
  • 111