std::ranges::data

Header: <ranges>

Returns a pointer to the first element of a contiguous range.

# Declarations

inline namespace /* unspecified */ {
inline constexpr /* unspecified */ data = /* unspecified */;
}

(since C++20) (customization point object)

Call signature
template< class T >
requires /* see below */
constexpr std::remove_reference_t<
ranges::range_reference_t<T>>* data( T&& t );

(since C++20)

# Notes

If the argument is an rvalue (i.e. T is an object type) and ranges::enable_borrowed_range<std::remove_cv_t> is false, the call to ranges::data is ill-formed, which also results in substitution failure.

If ranges::data(e) is valid for an expression e, then it returns a pointer to an object.

The C++20 standard requires that if the underlying data function call returns a prvalue, the return value is move-constructed from the materialized temporary object. All implementations directly return the prvalue instead. The requirement is corrected by the post-C++20 proposal P0849R8 to match the implementations.

# Example

#include <cstring>
#include <iostream>
#include <ranges>
#include <string>
 
int main()
{
    std::string s{"Hello world!\n"};
 
    char a[20]; // storage for a C-style string
    std::strcpy(a, std::ranges::data(s));
    // [data(s), data(s) + size(s)] is guaranteed to be an NTBS
 
    std::cout << a;
}

# See also