The documentation on std::string::c_str says:

"Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object."

Is this array dynamically allocated on calling c_str? If not where does it come from?

有帮助吗?

解决方案

For C++2003 this is up to the standard library implementation. The actual storage for it is most likely managed by the instance of std::string. Some implementations may use the internal buffer, some may use a separate pre-allocated buffer. It is a constant-time accessor though, so the options available to a library implementation are limited.

You shouldn't mess around with that memory outside what you are allowed to do by the standard though as you may fall flat on your face with a different implementation of the standard library.

Interestingly for C++11 this is a bit more defined, it must point to the internal buffer and be a synonym for std::string::data.

其他提示

Prior to C++11 it's unspecified. The string object manages it. With C++11, it points to the string objects data.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top