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.

5 Answers 5

8

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

Sign up to request clarification or add additional context in comments.

Comments

5

Yes, it is freed automatically.

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

Comments

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".

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.