std::basic_string<CharT,Traits,Allocator>:: c_str
|
const
CharT
*
c_str
(
)
const
;
|
(自 C++11 起为 noexcept)
(自 C++20 起为 constexpr) |
|
返回指向以空字符结尾的字符数组的指针,该数组包含与字符串中存储数据等效的数据。
该指针满足以下条件:范围
[
c_str
(
)
,
c_str
(
)
+
size
(
)
]
是有效的,且其中的值对应于字符串中存储的值,并在最后一个位置后包含一个额外的空字符。
从
c_str()
获取的指针可能因以下情况失效:
- 将字符串的非const引用传递给任何标准库函数,或
- 对字符串调用非const成员函数 ,不包括 operator[] 、 at() 、 front() 、 back() 、 begin() 、 rbegin() 、 end() 和 rend() (C++11 起) 。
写入通过
c_str()
访问的字符数组是未定义行为。
|
|
(C++11 起) |
目录 |
参数
(无)
返回值
指向底层字符存储的指针。
|
c_str
(
)
[
i
]
==
operator
[
]
(
i
)
对于每个在
|
(C++11 前) |
|
c_str
(
)
+
i
==
std::
addressof
(
operator
[
]
(
i
)
)
对于每个在
|
(C++11 起) |
复杂度
常量。
注释
从
c_str()
获取的指针仅当字符串对象不包含其他空字符时,才能被视为指向以空字符结尾的字符串的指针。
示例
#include <algorithm> #include <cassert> #include <cstring> #include <string> extern "C" void c_func(const char* c_str) { printf("c_func called with '%s'\n", c_str); } int main() { std::string const s("Emplary"); const char* p = s.c_str(); assert(s.size() == std::strlen(p)); assert(std::equal(s.begin(), s.end(), p)); assert(std::equal(p, p + s.size(), s.begin())); assert('\0' == *(p + s.size())); c_func(s.c_str()); }
输出:
c_func called with 'Emplary'
参见
|
(
DR*
)
|
访问首字符
(公开成员函数) |
|
(
DR*
)
|
访问末字符
(公开成员函数) |
|
返回指向字符串首字符的指针
(公开成员函数) |