Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are C++ strings mutable UNLIKE Java strings?

Tags:

c++

string

Is it alright to manipulate strings in C++ this way:

string s = "Sting"; s[2] = 'a'; 

It works alright (and prints 'Sting'), but is it safe to do so?

If yes, does this mean they are mutable?

like image 812
abcde Avatar asked Feb 10 '15 22:02

abcde


People also ask

Are strings in C mutable?

In general, C strings are mutable. The C++ language has its own string class. It is mutable. In both C and C++, string constants (declared with the const qualifier) are immutable, but you can easily “cast away” the const qualifier, so the immutability is weakly enforced.

Are strings mutable in Java?

Recall from Basic Java when we discussed snapshot diagrams that some objects are immutable: once created, they always represent the same value. Other objects are mutable: they have methods that change the value of the object. String is an example of an immutable type.

Why is String immutable in C?

A string is a sequential collection of characters that is used to represent text. The value of the String object is the content of the sequential collection of System. Char objects, and that value is immutable (that is, it is read-only).

Are strings immutable in Java?

Java String Pool is the special memory region where Strings are stored by the JVM. Since Strings are immutable in Java, the JVM optimizes the amount of memory allocated for them by storing only one copy of each literal String in the pool.


1 Answers

C++ string literals, i.e., something like "literal" are immutable although C++03 allowed assigning a pointer to such a literal to a char* (this privilege was deprecated and removed for C++11). Trying to change a character of a string literal is undefined behavior:

char* s = "literal"; // OK with C++03; illegal with C++11 and later s[0] = 'x';          // undefined behavior 

C++ std::string objects are certainly mutable assuming they are not declared as std::string const. If you consider the sequence of char objects to be independent of each other it is OK to assign to individual objects. It is, however, quite common that the strings actually contain Unicode encoded as UTF-8 bytes. If that's the case changing any element of the string may destroy the proper encoding, e.g., because a continuation byte gets replaced by something else.

So, yes, the strings are mutable but it may not be safe from a semantic point of view to assign to individual elements.

like image 193
Dietmar Kühl Avatar answered Sep 19 '22 15:09

Dietmar Kühl