std::basic_string::copy(3)

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

πŸ’– std::basic_string::copy(3) β€” C++ Standard Libary πŸ’–

🌸 NAME 🌸

std::basic_string::copy β€” std::basic_string::copy (yes bestie, it really said it twice πŸ’…)

πŸ¦‹ Synopsis πŸ¦‹

okay so here's the signature, copied exactly:

size_type copy( CharT* dest, size_type count, size_type pos
(constexpr since C++20)
= 0 ) const;

This one copies a substring [pos, pos + count) to the character string pointed to by dest. If the requested substring lasts past the end of the string, or if count == npos, the copied substring is [pos, size()).

The resulting character string is not null-terminated 😭 β€” no sneaky \0, bestie.

πŸŽ€ Parameters πŸŽ€

  • dest β€” pointer to the destination character string 🫢
  • count β€” length of the substring ✨
  • pos β€” position of the first character to include πŸ’–

⭐ Return value ⭐

Number of characters copied. That's the whole vibe, periodt.

🚨 Exceptions 🚨

std::out_of_range if pos > size().

If an exception is thrown for any reason, this function has no effect β€” strong exception safety guarantee, icon behavior ✨.

πŸ”₯ Complexity πŸ”₯

Linear in count. No cap.

πŸ“ Example πŸ“

The example, with its // Run this code note:

#include <iostream>
#include <string>

int main()
{
    std::string foo("WINE");

    // brace-initialization initializes all characters to 0,
    // providing a null-terminator
    char bar[4]{};

    // do not copy the last char, to guarantee null-termination
    foo.copy(bar, sizeof bar - 1);

    std::cout << bar << '\n'; // requires bar to be null-terminated
}

🌈 Output 🌈

WIN

🩹 Defect reports 🩹

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

  • LWG 847 β€” applied to C++98; behavior as published: there was no exception safety guarantee; correct behavior: added strong exception safety guarantee.

πŸ‘‘ See also πŸ‘‘

  • substr β€” returns a substring (public member function)
  • copy β€” copies characters (public member function of std::basic_string_view<CharT,Traits>)
  • copy β€” copies a range of elements to a new location
  • copy_if β€” (function template) (C++11)
  • memcpy β€” copies one buffer to another (function)
source/version + date: cppreference.com β€” 2024.06.10 β€” mwah, bye bestie πŸ’‹πŸŽ€
πŸ“¦ where this page comes from