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

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()).

# Declarations

size_type copy( CharT* dest, size_type count, size_type pos = 0 ) const;

(constexpr since C++20)

# Parameters

# Return value

Number of characters copied.

# Example

#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
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 847C++98there was no exception safety guaranteeadded strong exception safety guarantee

# See also