c++ - What does c_str() method from string class returns? -
i want access starting address of array maintained string class.
string str="hey"; char* pointer=(char*)str.c_str();
is pointer pointing address of array(maintained string class)? or string class create new array dynamic memory , copy existing string , return it's address?
if not right way, how access starting address of array maintained string class?
in c++11 standard it's explicitly stated .c_str()
(as newer .data()
) shall return pointer internal buffer used std::string
.
any modification of std::string after obtaining pointer via .c_str()
may result in said char *
returned became invalid (that - if std::string
internally had reallocate space).
in previous c++ standards implementation allowed return anything. standard not require user deallocate result, i've never seen implementation returning newly allocated. @ least gnu gcc's , msvc++'s stl string internally zero-terminated char arrays, returned c_str()
.
so it's safe assume (with normal c++ caution) in version of c++ in it's implementation .c_str()
return internal buffer.
in other words - should never ever keep value of .c_str()
unless 100% sure it's won't change it's size anytime in future (unless it's const
, is).
p.s. btw, should never ever char* pointer=(char*)str.c_str();
. it's const char *
, shall not modify contents, partly because above - may end-up overwriting memory of other object or corrupting internal state of std::string
, in case implementation doing fancy, indexing characters faster .find()
(newer seen that, hey - that's encapsulation!)
Comments
Post a Comment