psquid
psquid

Reputation: 829

Are strings in C++ copied when modified?

Using the std::string class in C++, it is possible to modify a character using the array notation, like:

std::string s = "Hello";
s[0] = 'X';
cout << s << '\n';

I have checked that this code compiles, and prints "Xello" as expected. However, I was wondering what the cost of this operation is: is it constant time, or is it O(n) because the string is copied?

Upvotes: 0

Views: 586

Answers (3)

Jamin Grey
Jamin Grey

Reputation: 10487

The string isn't copied. The internal data is directly modified.

It basically gets the internal data pointer of the actual string memory, and modifies it. Imagine doing this:

char *data = &str[0];
for(size_t i = 0; i < str.size(); ++i)
{
   data[i] = '!';
}

The code sets every character of the string to an exclamation mark. But if the string was copied, then after the first write, the data pointer would become invalid.

Or to use another example: std::cout << str[5] << std::endl;

That prints the 6th character of the string. Why would that copy the string? C++ can't tell the difference between char c = str[5] and str[5] = c (except as far as const vs non-const function calls go).

Also, str[n] is guaranteed to never throw exceptions, as long as n < str.size(). It can't make that guarantee if it had to allocate memory internally for a copy - because the allocation could fail and throw.

(As @juanchopanza mentioned, older C++ standards permitted CoW strings, but the latest C++ standard forbids this)

Upvotes: 1

marcinj
marcinj

Reputation: 49986

You can modify stl string like in you example, no copy will be done. Standard library string class does not manage string pool like other languages do for strings (like Java). This operation is constant in complexity.

Upvotes: 0

Blacktempel
Blacktempel

Reputation: 3995

You do only modify the first element s[0], therefore it can't be O(n). You don't copy the string.

Upvotes: 0

Related Questions