std::data - cppreference.com
来自cppreference.com
| 在标头 |
||
| 在标头 |
||
| 在标头 |
(C++23 起) |
|
| 在标头 |
(C++23 起) |
|
| 在标头 |
||
| 在标头 |
(C++26 起) |
|
| 在标头 |
||
| 在标头 |
||
| 在标头 |
||
| 在标头 |
(C++26 起) |
|
| 在标头 |
||
| 在标头 |
||
| 在标头 |
(C++20 起) |
|
| 在标头 |
(C++23 起) |
|
| 在标头 |
||
| 在标头 |
||
| 在标头 |
||
| 在标头 |
||
| 在标头 |
||
| 在标头 |
||
template< class C > constexpr auto data( C& c ) noexcept(noexcept(c.data())) -> decltype(c.data()); |
(1) | (C++17 起) |
template< class C > constexpr auto data( const C& c ) noexcept(noexcept(c.data())) -> decltype(c.data()); |
(2) | (C++17 起) |
template< class T, std::size_t N > constexpr T* data( T (&array)[N] ) noexcept; |
(3) | (C++17 起) |
返回指向含有范围元素的内存块的指针。
1,2) 返回 c.data()。
3) 返回 array。
参数
| c | - | 有 data() 方法的容器或视图
|
| array | - | 任意类型的数组 |
返回值
1,2) c.data()
3) array
异常
1,2) 在底层 c.data() 调用抛出时所抛出的异常
注解
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_nonmember_container_access |
201411L |
(C++17) | std::size()、 std::data() 和 std::empty()
|
__cpp_lib_initializer_list |
202511L |
(C++26) (DR11) |
std::initializer_list 的 data 与 empty 成员函数;移除 std::initializer_list 不需要的自由函数[1]
|
可能的实现
| 版本一 |
|---|
template<class C> constexpr auto data(C& c) noexcept(noexcept(c.data())) -> decltype(c.data()) { return c.data(); } |
| 版本二 |
template<class C> constexpr auto data(const C& c) noexcept(noexcept(c.data())) -> decltype(c.data()) { return c.data(); } |
| 版本三 |
template<class T, std::size_t N> constexpr T* data(T (&array)[N]) noexcept { return array; } |
示例
#include <cstring> #include <iostream> #include <string> int main() { std::string s{"Hello world!\n"}; char a[20]; // C-style 风格字符串的存储 std::strcpy(a, std::data(s)); // C++11 起 [s.data(), s.data() + s.size()] 保证为 NTBS std::cout << a; }
输出:
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| P3016R6 | C++17 | 1) 对 std::initializer_list 提供了非成员 std::data 重载2) 未要求 std::data 传播异常说明
|
1) 已移除 2) 已要求 |