I decided to return to C ++ after some time spent in Java, and now I'm completely confused about how strings work in C ++.
First, suppose we have a function:
void fun() { int a = 1; Point b(1,2); char c[] = "c-string"; }
As I understand it, a and b are allocated on the stack. c (pointer) is also allocated on the stack, but the content ("c-string") lives happily on the heap.
Q1: Is content c automatically released after the fun function completes?
Secondly, let us have a C ++ string :
void fun2() { (1) string s = "c++ string"; (2) s += "append"; (3) s = "new contents"; (4) s = "a" + s + "c"; }
String documentation is not too specific as to how strings work, so here are the questions:
Q2: Is the contents of s automatically freed upon completion of fun2 ?
Q3: What happens when we combine two lines? Should I care about memory usage? (line 2)
Q4: What happens when we overwrite the contents of a line (line 3) - but what about memory, should I worry? Is the originally allocated space reused?
Q5: What if I build such a line (line 4). It is expensive? Are string literals ( "a" , "c" ) a pool (for example, in Java) or are they repeated throughout the executable?
Ultimately, I'm trying to learn how to use strings correctly in C ++.
Thanks for reading this,
Queequeg