std::basic_string<CharT,Traits,Allocator>::append

Appends additional characters to the string.

# Declarations

basic_string& append( size_type count, CharT ch );

(constexpr since C++20)

basic_string& append( const CharT* s, size_type count );

(constexpr since C++20)

basic_string& append( const CharT* s );

(constexpr since C++20)

template< class SV >
basic_string& append( const SV& t );

(since C++17) (constexpr since C++20)

template< class SV >
basic_string& append( const SV& t, size_type pos,
size_type count = npos );

(since C++17) (constexpr since C++20)

basic_string& append( const basic_string& str );

(constexpr since C++20)

basic_string& append( const basic_string& str,
size_type pos, size_type count );

(until C++14)

basic_string& append( const basic_string& str,
size_type pos, size_type count = npos );

(since C++14) (constexpr since C++20)

template< class InputIt >
basic_string& append( InputIt first, InputIt last );

(constexpr since C++20)

basic_string& append( std::initializer_list<CharT> ilist );

(since C++11) (constexpr since C++20)

# Parameters

# Return value

*this

# Example

#include <cassert>
#include <string>
 
int main()
{
    std::string str = "std::string";
    const char* cptr = "C-string";
    const char carr[] = "range";
 
    std::string result;
 
    // 1) Append a char 3 times.
    // Note: This is the only overload accepting “CharT”s.
    result.append(3, '*');
    assert(result == "***");
 
    // 2) Append a fixed-length C-string
    result.append(cptr, 5);
    assert(result == "***C-str");
 
    // 3) Append a null-terminated C-string
    // Note: Because “append” returns *this, we can chain calls together.
    result.append(1, ' ').append(cptr);
    assert(result == "***C-str C-string");
 
    // 6) Append a whole string
    result.append(1, ' ').append(str);
    assert(result == "***C-str C-string std::string");
 
    // 7) Append part of a string
    result.append(str, 3, 2);
    assert(result == "***C-str C-string std::string::");
 
    // 8) Append range
    result.append(&carr[2], &carr[3]);
    assert(result == "***C-str C-string std::string::n");
 
    // 9) Append initializer list
    result.append({'p', 'o', 's'});
    assert(result == "***C-str C-string std::string::npos");
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 847C++98there was no exception safety guaranteeadded strong exception safety guarantee
LWG 2250C++98the behavior of overload (7) wasundefined if pos > str.size() is truealways throws an exception in this case
LWG 2788C++98overload (8) used a default constructedallocator to construct the temporary stringobtains the allocatorfrom get_allocator()
LWG 2946C++17overload (4) causes ambiguity in some casesavoided by making it a template

# See also