What's the difference between std::string::c_str and std::string::data? [duplicate]

元气小坏坏 提交于 2019-12-03 12:27:54

问题


Why would I ever want to call std::string::data() over std::string::c_str()? Surely there is some method to the standard's madness here...


回答1:


c_str() guarantees NUL termination. data() does not.




回答2:


c_str() return a pointer to the data with a NUL byte appended so you can use the return value as a "C string".

data() returns a pointer to the data without any modifications.

Use c_str() if the code you are using assumes a string is NUL terminated (such as any function written to handle C strings).




回答3:


Now in MS STL 10.0 there doesn't seem to be any difference, as I see this in the header:

...\Microsoft Visual Studio 10.0\VC\include\xstring

const _Elem *c_str() const
    {   // return pointer to null-terminated nonmutable array
    return (_Myptr());
    }

const _Elem *data() const
    {   // return pointer to nonmutable array
    return (c_str());
    }

So they return the same thing.



来源:https://stackoverflow.com/questions/1534399/whats-the-difference-between-stdstringc-str-and-stdstringdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!