关于string中data()和c_str()函数的几点区别
发布日期:2021-11-07 23:21:02 浏览次数:9 分类:技术文章

本文共 1677 字,大约阅读时间需要 5 分钟。

最近在看网上的一些源码的时候,遇到一个问题,大概是这样的。先上代码:

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

转载地址:https://blog.csdn.net/zhangwu416826/article/details/7826048 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:mangos源码分析--计划
下一篇:epoll使用详解

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月02日 20时26分25秒