This is rather awkward.
<string.h>
is a C header. It doesn't define string
. It looks like your version of <iostream>
directly or indirectly includes <string>
, or there would be an error.
Literal strings (those things that are delimited by paired quotation marks) may be pretty much anywhere, including a read-only memory segment. (They do take up memory, but you've got to have an awful lot of text to have a significant impact: something like War and Peace isn't going to take a full meg.) In this case, a std::string
is being initialized with that value, and later on has another value assigned to it. The std::string
handles the memory it uses.
There is, in C++, almost no reason to have a pointer to a std::string
. The std::string
doesn't take up much space without its contents, and it manages the memory for the contents itself. Are you confusing this with char *
?
You new
a std::string
for b
, and then you assign another address to b
without delete
ing the memory. That's a memory leak. What you new
ed for b
is still allocated out there, but there's no way to delete
it, so it will take up memory for the duration of the program.
Then, once you have assigned the address of a
to b
, you delete b;
. This is a Bad Idea, and will likely mess up something important in a probably unpredictable way. Only delete
memory you've acquired with new
. (The important thing here for delete
ing is not that b
is a pointer and should be deleted, but that the memory it points to was not gotten through new
.)
The memory management works something like this. A string literal is allocated somewhere. All you know is that you shouldn't try to change it or delete
it by any means. Use the value and don't touch the rest. A std::string
manages the memory for its own contents, and will take care of that in its destructor. A variable that's declared in a function or other block will be destroyed once it's out of scope (although whatever it might point to won't automatically be destroyed; only if it's a smart pointer or manages its own memory or whatever). If you new
memory, don't throw away the pointer value until it's delete
d. If you haven't new
ed memory, don't delete
it.