16

我为什么要打电话std::string::data()过去std::string::c_str()?当然,这里标准的疯狂有一些方法......

4

3 回答 3

19

c_str() 保证 NUL 终止。数据()没有。

于 2009-10-07T21:46:24.243 回答
6

c_str() 返回指向附加了 NUL 字节的数据的指针,因此您可以将返回值用作“C 字符串”。

data() 返回指向数据的指针,没有任何修改。

如果您使用的代码假定字符串是 NUL 终止的(例如为处理 C 字符串而编写的任何函数),请使用 c_str()。

于 2009-10-07T21:46:58.417 回答
1

现在在 MS STL 10.0 中似乎没有任何区别,正如我在标题中看到的那样:

...\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());
    }

所以他们返回同样的东西。

于 2011-07-06T22:07:02.533 回答