When learning. NET programming, you must have heard that the system. string class is an immutable string, that is, you cannot modify the value of a string.
For exampleCode
String S = " Hello " ;
S = " World " ;
Instead of changing the value of S to world, you generate a new string containing "world", and then reference the string "S" to a new string, the original string is discarded.
It is based on the unmodifiable string class that CLR uses the string interning technology to share the same string to reduce memory usage. For example, the following code
String S1 = " Hello " ;
String S2 = " Hello " ;
If (Object. referenceequals (S1, S2 ))
Console. writeline ( " They are same " );
S1 and S2 actually point to the same string.
So is there really no way to change the value of a string? Of course not. In C ++/CLI, we can use some special means to achieve our goal!
String ^ S1 = " Hello " ;
String ^ S2 = " Hello " ;
Interior_ptr < Char > P = Const_cast < Interior_ptr < Char > > (Ptrtostringchars (S1 ));
For (; * P; * P ++ = ' A ' );
Console: writeline ( " {0} and {1} " , S1, S2 );
Ptrtostringchars (string ^) is a definition in vcclr. h: A helper function in the header file. It returns an internal pointer of the interior_ptr <const char> type, pointing to the string contained in the string instance, the reason why the return type is interior_ptr <const char> instead of interior_ptr <char> is that we do not want to change the string in the string instance, but since we insist on doing so, so let's use a const_cast <t> to remove this const!
Run the above Code and you will find that the content of S2 is AAAAA, Not hello.
Of course, the above example only describes the possibility of modifying the content of the string instance, and does not encourage everyone to do so. Although direct access to strings inside the string instance may bring some performance benefits. However, because of the existence of string interning, modifying the string inside the string instance is quite risky. For example, in the above example, you will find that the output of S1 is also aaaaa!