开发者

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

This question already has answers h开发者_StackOverflow中文版ere: string c_str() vs. data() (6 answers) Closed 8 years ago.

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...


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


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜