九棠:delete this;这种自杀性的语法该怎么用

来源:百度文库 编辑:高校问答 时间:2024/05/10 06:20:36
delete this;
我从书上看到这种用法,并且按照书上变了一个类,编译没有问题,但运行时却出了问题怎么回事,有谁能解释一下这种用用法该怎么用吗。
下面这个是书上提供的string的升级版本,存在这种问题,请高人看看。
#include "iostream.h"
#include "string"
class bstring
{
private:
class string_rep{ //嵌套类
public: //非嵌套类需要声明友元
int use_count;
char* chars;
public:
string_rep(const char*);
string_rep(const string_rep&);
~string_rep();
void increment();
void decerment();
const string_rep&
operator=(const string_rep&); //const的用法
};
string_rep* rep;
public:
bstring(const char* =""); // *与=之间需要加空格
bstring(const bstring&);
~bstring();
const bstring& operator=(const bstring&);
//我的理解:返回值为引用就是返回当前对象,
//非引用返回的是临时对象
};
//嵌套类的实现
bstring::string_rep::string_rep(const char* cp):use_count(0),
chars(new char[strlen(cp)+1]){
strcpy(chars,cp);
cout<<"string_rep构造函数被调用"<<endl;
}
bstring::string_rep::~string_rep(){delete[]chars;cout<<"string_rep析构函数被调用"<<endl;}
bstring::string_rep::string_rep(const bstring::string_rep& orig):use_count(0),
chars(new char[strlen(orig.chars)+1]){
strcpy(chars,orig.chars);
cout<<"string_rep拷贝构造函数被调用"<<endl;
}
//两个重要的地方
void bstring::string_rep::increment(){
++use_count;
}
void bstring::string_rep::decerment(){
if(--use_count==0)
delete[] this;
cout<<"string_rep对象被删除"<<endl;
}
//................................................
const bstring::string_rep& bstring::string_rep::operator=(const bstring::string_rep& orig){
//注意返回类型
if(this!=&orig){
delete[]chars;
chars=new char[strlen(orig.chars)+1];
strcpy(chars,orig.chars);
}
return *this;
}
//bstring类的实现
bstring::bstring(const char* c):rep(new string_rep(c)){
rep->increment();
cout<<"bstring的构造函数被调用"<<endl;

}
bstring::~bstring(){
rep->decerment();
cout<<"bstring的析构函数被调用"<<endl;
}
bstring::bstring(const bstring& s):rep(s.rep){
rep->increment();
cout<<"bstring的拷贝构造函数被调用"<<endl;
}
const bstring& bstring::operator=(const bstring& s){
if(rep!=s.rep){
rep->decerment();
rep=s.rep;
rep->increment();
}
return *this;
}

你问的哪个具体,我会也想帮你