std::basic_string::assign(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’… std::basic_string::assign β€” the C++ Standard Library's glow-up button

ok so bestie, welcome to std::basic_string::assign, a page straight out of the C++ Standard Library and honestly? she's that girl. this is the member function that lets you replace the entire contents of a string in one move β€” no cap, it's giving "new year new me" but for basic_string. πŸ¦‹


✨ Synopsis ✨

no literally there are ten overloads, so buckle up, we're doing all of them πŸ’–

basic_string& assign( size_type count, CharT ch );            // (1)  (constexpr since C++20)

basic_string& assign( const basic_string& str );              // (2)  (constexpr since C++20)

overload (3) had a glow-up, so here's both versions:

// (until C++14)
basic_string& assign( const basic_string& str,
                      size_type pos, size_type count );

// (since C++14)  (constexpr since C++20)
basic_string& assign( const basic_string& str,
                      size_type pos, size_type count = npos );
// (since C++11)  (constexpr since C++20)
basic_string& assign( basic_string&& str )                    // (4)
    noexcept(/* see below */);

basic_string& assign( const CharT* s, size_type count );      // (5)  (constexpr since C++20)

basic_string& assign( const CharT* s );                       // (6)  (constexpr since C++20)

// (constexpr since C++20)
template< class InputIt >
basic_string& assign( InputIt first, InputIt last );          // (7)

// (since C++11)  (constexpr since C++20)
basic_string& assign( std::initializer_list<CharT> ilist );   // (8)

// (since C++17)  (constexpr since C++20)
template< class StringViewLike >
basic_string& assign( const StringViewLike& t );              // (9)

// (since C++17)  (constexpr since C++20)
template< class StringViewLike >
basic_string& assign( const StringViewLike& t,                // (10)
                      size_type pos, size_type count = npos );

Replaces the contents of the string. that's the whole vibe. πŸ”₯


πŸŽ€ Description πŸŽ€ (yes, all ten, i'm not skipping a single one)

  1. Replaces the contents with count copies of character ch. simple, cute, iconic.
  2. Replaces the contents with a copy of str. Equivalent to *this = str;. and heads up β€” in particular, allocator propagation may take place (since C++11). she's bringing her whole entourage, ok?
  3. Replaces the contents with a substring [pos, pos + count) of str. If the requested substring lasts past the end of the string, or if count == npos, the resulting substring is [pos, str.size()). If pos > str.size(), std::out_of_range is thrown. ⚠️ bestie, watch that pos.
  4. Replaces the contents with those of str using move semantics. Equivalent to *this = std::move(str). In particular, allocator propagation may take place. she literally took everything and left.
  5. Replaces the contents with copies of the characters in the range [s, s + count). This range can contain null characters. \0 girlies rise πŸ™ˆ
  6. Replaces the contents with those of the null-terminated character string pointed to by s. The length of the string is determined by the first null character using Traits::length(s).
  7. Replaces the contents with copies of the characters in the range [first, last). This overload does not participate in overload resolution if InputIt does not satisfy LegacyInputIterator (since C++11).
  8. Replaces the contents with those of the initializer list ilist. {'i','c','o','n','i','c'} energy ✨
  9. Implicitly converts t to a string view sv as if by std::basic_string_view<CharT, Traits> sv = t;, then replaces the contents with those of sv, as if by assign(sv.data(), sv.size()). This overload participates in overload resolution only if std::is_convertible_v<const StringViewLike&, std::basic_string_view<CharT, Traits>> is true and std::is_convertible_v<const StringViewLike&, const CharT*> is false. (iykyk πŸ’€)
  10. Implicitly converts t to a string view sv as if by std::basic_string_view<CharT, Traits> sv = t;, then replaces the contents with the characters from the subview [pos, pos + count) of sv. If the requested subview lasts past the end of sv, or if count == npos, the resulting subview is [pos, sv.size()). If pos > sv.size(), std::out_of_range is thrown. This overload participates in overload resolution only if std::is_convertible_v<const StringViewLike&, std::basic_string_view<CharT, Traits>> is true and std::is_convertible_v<const StringViewLike&, const CharT*> is false.

🫢 Parameters 🫢

  • count β€” size of the resulting string
  • pos β€” index of the first character to take
  • ch β€” value to initialize characters of the string with
  • first, last β€” range to copy the characters from
  • str β€” string to be used as source to initialize the characters with
  • s β€” pointer to a character string to use as source to initialize the string with
  • ilist β€” std::initializer_list to initialize the characters of the string with
  • t β€” object (convertible to std::basic_string_view) to initialize the characters of the string with

🌸 Type requirements 🌸

  • InputIt must meet the requirements of LegacyInputIterator.

πŸ’– Return value πŸ’–

*this

that's it. she returns herself. main character energy, honestly πŸ‘‘


🌈 Complexity 🌈

  1. Linear in count.
  2. Linear in size of str.
  3. Linear in count.
  4. Constant. If alloc is given and alloc != other.get_allocator(), then linear.
  5. Linear in count.
  6. Linear in size of s.
  7. Linear in distance between first and last.
  8. Linear in size of ilist.
  9. Linear in size of t.

πŸ’€ Exceptions πŸ’€

Overload 4) has this noexcept specification, and it's a whole mood:

noexcept(std::allocator_traits<Allocator>::
             propagate_on_container_move_assignment::value ||
         std::allocator_traits<Allocator>::is_always_equal::value)

If the operation would result in size() > max_size(), throws std::length_error.

🫢 If an exception is thrown for any reason, this function has no effect (strong exception safety guarantee). yes bestie, she's atomic-ish about it. your string is safe.

🧚 Example 🧚

// Run this code

#include <iostream>
#include <iterator>
#include <string>

int main()
{
    std::string s;
    // assign(size_type count, CharT ch)
    s.assign(4, '=');
    std::cout << s << '\n'; // "===="

    std::string const c("Exemplary");
    // assign(const basic_string& str)
    s.assign(c);
    std::cout << c << " == " << s << '\n'; // "Exemplary == Exemplary"

    // assign(const basic_string& str, size_type pos, size_type count)
    s.assign(c, 0, c.length() - 1);
    std::cout << s << '\n'; // "Exemplar";

    // assign(basic_string&& str)
    s.assign(std::string("C++ by ") + "example");
    std::cout << s << '\n'; // "C++ by example"

    // assign(const CharT* s, size_type count)
    s.assign("C-style string", 7);
    std::cout << s << '\n'; // "C-style"

    // assign(const CharT* s)
    s.assign("C-style\0string");
    std::cout << s << '\n'; // "C-style"

    char mutable_c_str[] = "C-style string";
    // assign(InputIt first, InputIt last)
    s.assign(std::begin(mutable_c_str), std::end(mutable_c_str) - 1);
    std::cout << s << '\n'; // "C-style string"

    // assign(std::initializer_list<CharT> ilist)
    s.assign({'C', '-', 's', 't', 'y', 'l', 'e'});
    std::cout << s << '\n'; // "C-style"
}

⭐ Output ⭐

====
Exemplary == Exemplary
Exemplar
C++ by example

C-style
C-style
C-style string

C-style

(no bestie i don't know why there's a blank line either, but it's canon, i don't make the rules πŸ’…)


πŸ“‹ Defect reports πŸ“‹

The following behavior-changing defect reports were applied retroactively to previously published C++ standards. (yes, the committee went back and edited the group chat 😭)

  • LWG 847 β€” applied to C++98 β€” behavior as published: there was no exception safety guarantee β†’ correct behavior: added strong exception safety guarantee
  • LWG 2063 β€” applied to C++11 β€” behavior as published: non-normative note stated that swap is a valid implementation of move-assign β†’ correct behavior: corrected to require move assignment
  • LWG 2579 β€” applied to C++11 β€” behavior as published: assign(const basic_string&) did not propagate allocators β†’ correct behavior: made to propagate allocators if needed
  • LWG 2946 β€” applied to C++17 β€” behavior as published: overload (9) caused ambiguity in some cases β†’ correct behavior: avoided by making it a template

πŸ‘€ See also πŸ‘€

  • assign_range (C++23) β€” assign a range of characters to a string (public member function)
  • constructor β€” constructs a basic_string (public member function)
  • operator= β€” assigns values to the string (public member function)

πŸ“ Category πŸ“

  • conditionally noexcept

that's the whole page bestie, go forth and reassign your strings with confidence 🫢✨

🌸 sourced from http://cppreference.com, dated 2024.06.10 β€” this was std::basic_string::assign(3), and honestly? she ate. periodt. πŸ’…πŸ‘‘
πŸ“¦ where this page comes from