I’ve decided to come back to C++ after some time spent in Java and now I’m quite confused about how strings work in C++.
To start with, suppose we have a function:
void fun() {
int a = 1;
Point b(1,2);
char c[] = "c-string";
}
As I understand, a and b are allocated on the stack. c (the pointer) is allocated on the stack too, but the contents (“c-string”) live happily on the heap.
Q1: Are the contents of c automatically deallocated when the function fun ends?
Secondly let’s suppose we 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 isn’t too specific about how the strings work, so here are the questions:
Q2: Are the contents of s automatically deallocated after fun2 ends?
Q3: What does happen when we concatenate two strings? Should I care about memory usage? (line 2)
Q4: What happens when we overwrite the contents of a string (line 3) – what about memory, should I worry? Is the originally allocated space reused?
Q5: What if I construct a string like this (line 4). Is it expensive? Are string literals ("a","c") pooled (like in Java) or repeated throughout the final executable?
What I am ultimately trying to learn is how to correctly use strings in C++.
Thanks for reading this,
Queequeg
That’s wrong, they all live in automatic memory (the stack). Even the
chararray. In C++, a string is an object of typestd::string.Yes.
Yes.
They are concatenated, and the memory is managed automatically. (assuming we’re talking about
std::stringand notchar[]orchar*.Implementation detail. It can be reused, it can be re-allocated if the previous memory can’t hold the new contents.
String literals can be pooled, but it’s not required. For large concatenation, it’s usual to use a
std::stringstreaminstead (similar to Java). But profile first, don’t do premature optimizations. Not that neither of those are string literals though.This resides in read-only memory and can’t be modified.
Use a
std::string.