本机windows系统安装了VS2008环境下,查看xstring文件的源码发现xstring类的c_str(),data()实现如下
const _Elem *__CLR_OR_THIS_CALL c_str() const { // return pointer to null-terminated nonmutable array return (_Myptr()); } const _Elem *__CLR_OR_THIS_CALL data() const { // return pointer to nonmutable array return (c_str()); }
这难道有区别吗???
写了个测试代码如下:
#include<stdio.h> #include<cstring> #include<string> using std::string; int _tmain(int argc, _TCHAR* argv[]) { sTopic = "hello world"; const char* pC_str = sTopic.c_str(); printf("sTopic.c_str()=%d, sizeof(...)=%d, strlen(...)=%d\n", pC_str, sizeof(sTopic.c_str()), strlen(pC_str) ); const char* pData = sTopic.data(); printf("sTopic.data()=%d, sizeof(...)=%d, strlen(...)=%d\n", pData, sizeof(sTopic.data()), strlen(pData) ); char * pTemp = const_cast<char*>(sTopic.c_str() ); pTemp[0] = 'a'; printf("modify [0]='a' after const_cast(sTopic.c_str() ) sTopic=%s\n", sTopic.c_str() ); pTemp = const_cast<char*>(sTopic.data() ); pTemp[1] = 'b'; printf("modify [1]='b' after const_cast(sTopic.data() ) sTopic=%s\n", sTopic.c_str() ); return 0; }
结果是:
sTopic.c_str()=23859240, sizeof(...)=4, strlen(...)=11
sTopic.data()=23859240, sizeof(...)=4, strlen(...)=11
modify [0]='a' after const_cast(sTopic.c_str() ) sTopic=aello world
modify [1]='b' after const_cast(sTopic.data() ) sTopic=abllo world