String assignment to another string is by value or reference?

1264 views c++
1

I have the following code:

string line1;
string line2;

line1 = "this";
line2 = line1;
line1.replace(0, 1, "T");
cout << "line1: " << line1 << "  line2: " << line2 << endl;

The output is:

line1: This line2: this

So it looks like line1 and line2 do not point at the same string object.

This is confusing for me, as I thought that since c++ strings are mutable, changing s1 should also change s2.

answered question

3 Answers

6

Objects in C++ generally have value semantics.

That's because all the primitive types (such as int, double, char, etc.) work like that, and the types in the standard library (such as std::string, std::vector, std::map, etc.) were modeled after primitive types.

Thus:

string line1;
string line2;

means you have two entirely separate string objects. They're not references or pointers (like in e.g. Java), they are full objects themselves.

Then

line2 = line1;

does not mean line2 refers to the same underlying object as line1 (it cannot mean that because line2 is not a reference or pointer); it means the contents of the line1 object are copied into the line2 object. Any later changes to line1 are not visible in line2 because it is an independent copy.

posted this
4

They're mutable, but they're not references unless you declare them to be (and both were declared string, not string&). The line:

line2 = line1;

invokes copy assignment (had you declared and initialized it at the same time, it would have been copy construction, but there is no meaningful difference in this case), initializing line2 to the same value as line1, but completely independent of line1 from then on.

posted this
9

In C++, string assignments are by value, not by reference.

If you want to copy a string by reference, you can do this:

string line1;
string line2;

line1 = "hi"; // line1 = "hi", line2 is empty
&line2 = &line1; // this changes the location (in memory) of line2 to the location of line1. 
// The two are now essentially the same thing. After this, line2 = "Hi". 
line1 = "bye"; // line2 now equals "bye", as they are set to the same "chunk" of memory

NOTE - I didn't actually compile this code, but it should work.

For more information, read though this, and look into pointers.

posted this

Have an answer?

JD

Please login first before posting an answer.