C++字符串拼接:append方法与赋值加法运算符该如何选择?
operator+= or append for C++ Strings? Great question—this is a common point of confusion, especially since both seem to do the same thing at first glance. Let’s break down when to choose each, their historical differences, and how to handle partial string appends.
Core Overlap & Modern Equivalence
For simple cases where you’re appending an entire string, C-style char array, or single character, operator+= and append are functionally identical in modern C++ (C++11 and later). The standard explicitly defines basic_string::operator+= to behave the same as calling the corresponding append overload. For example:
std::string s = "foo"; s += "bar"; // Same as s.append("bar"); s += '!'; // Same as s.append(1, '!');
In practice, compilers optimize both to nearly identical machine code here—so the choice comes down to readability, not performance.
When to Choose Which
Go with operator+= for Readability
If you’re just tacking on an entire string or single character, += is more concise and intuitive. It reads like natural language ("add this to the string"), making your code easier to scan at a glance. Most C++ developers will default to += for these simple cases.
Use append for Fine-Grained Control
append shines when you need more than just full-string appends—it has several overloads that operator+= doesn’t support:
- Append only part of a string: Use
append(const char* str, size_t count)to take the firstcountcharacters from a C-style array, orappend(const std::string& str, size_t pos, size_t count)to slice a substring from another string. Example:std::string s = "Hello"; s.append(" World!", 6); // Adds " World" (first 6 chars) std::string other = "foo bar baz"; s.append(other, 4, 3); // Adds "bar" (starts at index 4, takes 3 chars) - Repeat a character multiple times: Use
append(size_t count, char c)to add the same charactercounttimes. This is way cleaner than looping with+=:std::string s = "Count: "; s.append(5, '*'); // Adds "*****" → "Count: *****"
Historical Differences
You’re right to suspect there were differences in the past! In early C++ standards (like C98), operator+= had fewer overloads—for example, it didn’t support appending a substring directly. Some older compiler implementations also optimized append better for certain cases, like pre-allocating memory more efficiently. But these gaps have been closed in modern C; today, the only meaningful differences are the extra features append provides.
Summary
- Use
+=for simple, full-string or single-character appends (cleaner, more readable). - Use
appendwhen you need partial string slices, repeated characters, or other advanced control. - Historically, there were gaps in functionality and performance, but modern C++ has aligned the two for overlapping use cases.
内容的提问来源于stack exchange,提问作者Jonathan Mee




