std::basic_string<CharT,Traits,Allocator>::copy
From cppreference.com
< cpp | string | basic string
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
std::basic_string
Literals
Helper classes
Deduction guides (C++17)
(C++23)
(DR*)
(DR*)
(C++23)
(DR*)
(C++23)
(C++23)
basic_string::copy
(C++20)
(C++20)
(C++23)
(C++20)(C++20)
(until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20)
(C++11)(C++11)(C++11)
(C++11)(C++11)
(C++14)
(C++11)
size_type copy( CharT* dest, size_type count, size_type pos = 0 ) const;
(constexpr since C++20)
Copies a substring [
pos,
pos + count)
to 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.
Contents
[edit] Parameters
dest
-
pointer to the destination character string
count
-
length of the substring
pos
-
position of the first character to include
[edit] Return value
Number of characters copied.
[edit] 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).
[edit] Complexity
Linear in count.
[edit] Example
Run this code
#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
[edit] Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
LWG 847 | C++98 | there was no exception safety guarantee | added strong exception safety guarantee |