最近在看网上的一些源码的时候,遇到一个问题,大概是这样的。先上代码:
class bin_decoder_t
{
public:
explicit bind_decoder_t(const string& src_)
{
m_ptr = src_.data();
m_remain_size = src.size();
}
private:
const char* m_ptr;
uint32_t m_remain_size;
};
类似序列化的一个类,问题出在第6行,用data()?还是用c_str()呢?下面列出这两个函数的几点解释:
1.const char* string::c_str () const:
(1)Returns the contents of the string as a C-string (an array of characters that has the null character '\0 ' appended).
(2)The return value is owned by the string. Thus, the caller must neither modify nor free or delete the return value.
(3)The return value is valid only as long as the string exists, and as long as only constant functions are called for it.
2.const char* string::data () const
(1)Returns the contents of the string as a character array.
(2)The return value contains all characters of the string without any modification or extension. In particular, no null character is appended. Thus, the return value is, in general, not a valid C-string.
(3)The return value is owned by the string. Thus, the caller must neither modify nor free or delete the return value.
(4)The return value is valid only as long as the string exists, and as long as only constant functions are called for it.
看了上面的解释你心中肯定会有答案了:也就是bin_decoder_t的成员指针指向一个string内部的地址,这样是不能持久化的,当string析构时,m_ptr就成了野指针,注意在平时代码时要尽量避免一个类成员指针,指向一个外部地址(特别是局部变量地址)正确的做法是实现深拷贝,这里就不在赘述。
但是目前在VS2010中查看string的源码得知,c_str()和data的代码如下:
...\Microsoft Visual Studio10.0\VC\include\xstring
const _Elem *c_str() const
{ // return pointer tonull-terminated nonmutable array
return (_Myptr());
}
const _Elem *data() const
{ // return pointer tononmutable array
return (c_str());
}
那么我是否可以认为他们没有区别呢?can you tell me???