std string 的 c_str 的问题重新探讨
下面程序:
int main(void)
{
const char *mystr = NULL;
//使用MYString,类代码在后面;
MYString *pmystr = new MYString("This is mystring");
mystr = pmystr->str();
cout << mystr << endl;
delete mystr; //删掉mystr
cout << pmystr->str() << endl;//输出空的,上面删除起作用了。
const char *pstr2 = NULL;
//使用std string类
string *str2 = new string("This is std string");
pstr2 = str2->c_str();
cout << pstr2 << endl; //输出"This is std string".
delete pstr2;//删掉mystr,类似操作
cout << str2->c_str() << endl; //还是输出"This is std string"
}
下面是MYString类代码,
//mystring.h
#ifndef _MYSTRING_H_
#define _MYSTRING_H_
class MYString {
private:
char* _str;
public:
MYString(const char *str = NULL); //default constructor
MYString(const MYString &other); //copy constructor
MYString& operator=(const MYString &other); //operator overload
~MYString(void); //destructor
const char* str(void) const; //自定义str函数,对应标准string的c_str()函数;
};
#endif
///////////////////////////////////////////////////
//mystring.cpp
#include<iostream>
#include "mystring.h"
using namespace std;
MYString::MYString(const char *str) {
if(str == NULL){
_str = new char[1];
_str[0] = '\0';
} else {
_str = new char[strlen(str)+1];
if(_str == NULL) {
cout << "Error occured in constructor of MYString!"
<<endl;
exit(1);
}
strcpy(_str, str); //strcpy will add '\0' automatically to _str
}
}
MYString::MYString(const MYString &other) {
int len = strlen(other._str);
_str = new char[len + 1];
strcpy(_str, other._str);
}
MYString& MYString::operator=(const MYString &other) {
if(this == &other) {
return *this;
}
delete [] _str; //release original resource
_str = new char[strlen(other._str) + 1];
strcpy(_str, other._str);
return *this; //return *this
}
MYString::~MYString(void) {
if(_str != NULL) {
delete [] _str;
_str = NULL;
}
}
const char* MYString::str(void) const{
return _str;
}
/////////////////////end//////////////////////////////
问题,
1,为什么MYstring的str返回的const 指针被删除了?而标准的string的
c_str返回的没被删除?
2, 标准的string的c_str怎么实现的?
3, 如何避免调用者修改类似于MYstring的c_str()返回的指针内容(如通过\p[2] = 'x' 等方法)?