Reputation:
I've got 2 questions:
Upvotes: 0
Views: 888
Reputation: 595402
How much RAM does string variable use?
C++ has no concept of RAM. It knows only about static memory, automatic memory, and dynamic memory. How those are implemented depend on the particular details of the OS and compiler.
A string
object is typically stored in automatic memory (such as on a thread's stack), unless you explicitly allocate it in dynamic memory (such as on a heap) via the new
operator. If the string
is a member of a class/struct that is allocated with new
, but itself is not new
'ed, then it is in automatic memory that just happens to be backed by dynamic memory.
Is it 28 bytes and no matter how many chars it consists of?
In any case, sizeof(string)
number of bytes are allocated, which may or may not be 28 bytes, depending on the string
's particular implementation. But yes, the size of a string
object is fixed at compile-time and does not change at runtime, regardless of how many characters are stored inside the string.
What if length of such string is more than 28 chars? Does it take 2x more (56 bytes) or not?
A string
's character data is usually allocated in dynamic memory (unless the length is small and the string
implements "Short String Optimization"). The allocated size will always be the string
's capacity
(plus a little overhead from the string
's allocator
). But how much capacity
is used is up to the string
's particular implementation to decide. And while the capacity
can grow as characters are added, how much it grows at a time is determined by the implementation.
Upvotes: 3