Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::basic_string::assign — replace a string’s contents

Choose the overload that matches your source. For a buffer with a known length, pass a pointer and a count to preserve embedded null characters.

Version: ISO C++23; implementation support may vary

Syntax

// ISO C++23 member declarations inside std::basic_string<CharT, Traits, Allocator> (<string>)
constexpr basic_string& assign(const basic_string& str);
constexpr basic_string& assign(basic_string&& str)
    noexcept(std::allocator_traits<Allocator>::propagate_on_container_move_assignment::value ||
             std::allocator_traits<Allocator>::is_always_equal::value);
constexpr basic_string& assign(const basic_string& str, size_type pos, size_type count = npos);
// Both templates require implicit conversion from const T& to std::basic_string_view<CharT, Traits>.
// Only the whole-source template also requires that const T& not be implicitly convertible to const CharT*.
template<class T> constexpr basic_string& assign(const T& t);
template<class T> constexpr basic_string& assign(const T& t, size_type pos, size_type count = npos);
constexpr basic_string& assign(const CharT* p, size_type count);
constexpr basic_string& assign(const CharT* p);
constexpr basic_string& assign(size_type count, CharT ch);
// InputIt must qualify as an input iterator.
template<class InputIt> constexpr basic_string& assign(InputIt first, InputIt last);
constexpr basic_string& assign(std::initializer_list<CharT> ilist);

std::basic_string::assign, declared in <string>, replaces the entire contents of an existing string, including a std::string. It returns *this by reference, so calls can be chained. Unlike append, it does not add to the end. The whole-basic_string overloads behave like copy and move operator=. A move need not take over the source buffer, and its noexcept condition depends on allocator traits.

assign(p, count) copies exactly count CharT elements, including embedded \0 characters. [p, p + count) must be a valid readable range; the function cannot check the buffer’s extent. Validate an untrusted count against the available data before calling. In contrast, assign(p) requires a valid null-terminated string and copies only up to, but not including, the first null.

assign(src, pos, count) takes a slice of a string or a view-like source. The count is capped at the remaining length; omitting it or passing npos means through the end. pos == size() gives an empty result, while pos > size() for the source throws std::out_of_range. Both view-like templates (since C++17) require implicit conversion from const T& to the matching std::basic_string_view. Only the whole-source template excludes implicit conversion from const T& to const CharT*; the template with pos and count has no such restriction.

assign(count, ch) stores count copies of ch, assign(first, last) copies a valid half-open range of input iterators, and assign({…}) copies an initializer list. assign_range(r) is a separate C++23 member; its availability depends on the standard library implementation.

Copying does not leave a view into the source, but source data must stay valid while it is read. After a successful assignment, reacquire pointers, references, iterators, and views into the old destination contents: they may have been invalidated. A result larger than max_size() throws std::length_error. If the member throws, the destination is unchanged; an invalid range is undefined behavior, not a guaranteed exception.

Examples

#include <iostream>
#include <string>
#include <string_view>

int main() {
    const char buffer[] = {'I', 'D', ':', 'A', '\0', 'B'};
    const std::string_view record{buffer, sizeof buffer};
    const auto separator = record.find(':');
    if (separator == std::string_view::npos) {
        std::cerr << "missing separator\n";
        return 1;
    }

    const auto start = separator + 1;
    std::string field = "old";
    field.assign(record.data() + start, record.size() - start);

    std::cout << "size=" << field.size() << '\n';
    std::cout << "preserved="
              << (field == std::string("A\0B", 3) ? "yes" : "no") << '\n';
}

Result

size=3
preserved=yes

The code checks the result of `find` against `npos` before computing the offset past the required `:` separator. The buffer has no trailing null; the explicit count copies all three field elements, `A`, `\0`, and `B`.

Related lessons

  • C++ · Lesson 58 · Advanced · Version: 3

Sources