Reputation: 1975
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.
Upvotes: 2
Views: 134
Reputation: 89189
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.
Upvotes: 1
Reputation: 25083
Yes, it is freed automatically.
I suggest cplusplus.com for a handy online reference to STL.
Upvotes: 5
Reputation: 76825
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.
Upvotes: 1
Reputation: 224159
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"
.
Upvotes: 1
Reputation: 7982
std::string handles it's own memory, so when you use s = "value_new", the string "value_old" is sent to oblivion.
Upvotes: 8