3 ms·
std::string isn't null-terminated. You need to use .c_str(), which allocates a copy that is destroyed when the string is changed (or is destructed).
by jcranmer 8y ago
std::string isn't null-terminated. You need to use .c_str(), which allocates a copy that is destroyed when the string is changed (or is destructed).
- TimJYoung 8y agoAhh, yes, forgot about that - thanks !
- thestoicattack 8y agoIt seems[1] that since C++11 .data() and .c_str() are the same function. c_str() is also documented as having constant complexity. If it made a copy, wouldn't it have to be linear? [1] https://en.cppreference.com/w/cpp/string/basic_string/data https://en.cppreference.com/w/cpp/string/basic_string/data
- gpderetta 8y agoYes. Allocating on demand was a legal implementation before c++11. No standard library made use of the option and the latitude was removed in c++11. I think it is still allowed to null terminate on demand.
- hermitdev 8y agoIt doesn't have to make a copy. std::string is always null-terminated as of C++11.
- vortico 8y agoIn practice, all modern C++ compilers and standard libraries just set a null character to the c_str()[len] position and reallocate the string if the capacity of the string buffer cannot contain the extra byte. It is never a linear operation unless you're working with old or niche C++ compilers. In C++11 this is required in the standard.