问题描述
如果我需要在情境中从 std :: string
中获取NUL终止的 char
数组在哪里我需要确保什么都不会分配,是否安全使用 c_str
这样做?例如,如果我在一个析构函数中,并且我想从 string
复制一些数据到一个预先分配的固定大小的缓冲区,我可以使用<$ c
If I need to get a NUL-terminated char
array out of a std::string
in a situation where I need to be sure nothing will be allocated, is it safe to use c_str
to do so? For example, if I'm inside a destructor and I want to copy some data from a string
into a pre-allocated, fixed-size buffer, can I use c_str
and be sure it won't throw anything?
推荐答案
标准说:调用 c_str()
可能使引用,指针和操作符无效,引用 string
的元素,
The standard says that calling c_str()
may invalidate references, pointers, and interators referring to the elements of the string
, which implies that reallaocation is permitted (21.3/5 "Class template basic_string").
你可能只需调用 string :: copy()
获取您的副本(如果需要,您需要自己添加null终止符)。
You might want to just call string::copy()
to get your copy (you'll need to add the null terminator yourself if you need it).
这篇关于是string :: c_str()允许在堆上分配任何东西吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!