MRK*_*187 0 c++ pointers destructor operator-overloading
嗨我有一个测试tomarrow,无法弄清楚为什么在检查引用是否为0之前对指针进行减法.我一直在搜索谷歌,但仍然无法弄明白.所以我希望转向你们:)会有所帮助.最简单的只是向您展示代码,我已经用注释标记了行,所以这里是:
这是StringRep类,它有指向它的指针,用于计算指向它的pointerref,
struct StringRep{
int size; // amount of chars incl. EOL \0-tecken
char* chars; // Pointer to char
int refCount; // Amount of String-variables
};
Run Code Online (Sandbox Code Playgroud)
这是使用StringRep的类String,
class String{
public:
String(char* str);
String(const String& other);
~String();
const String& operator=(const String& rhs);
char get(int index) const { return srep->chars[index]; }
void put(char ch, int index);
private:
StringRep* srep;
};
String::String(const String& other):srep(other.srep){
srep->refCount++;
}
String::~String(){
if (--srep->refCount == 0){ //why --srep here?
delete [] srep->chars;
delete srep;
}
}
const String& String::operator=(const String& rhs){
if (srep != rhs.srep){
if (--srep->refCount == 0){ //why --srep here?
delete [] srep->chars;
delete srep;
}
srep = rhs.srep;
srep->refCount++;
}
return *this;
}
void String::put(char ch, int index){
if (srep->refCount > 1){ //Why not --srep here?
StringRep* tmpRep = new StringRep;
tmpRep->refCount = 1;
tmpRep->size = srep->size;
tmpRep->chars = new char[tmpRep->size];
std::strcpy(tmpRep->chars, srep->chars);
--srep->refCount;
srep = tmpRep;
}
srep->chars[index] = ch;
}
Run Code Online (Sandbox Code Playgroud)
这是关于测试的示例问题的所有信息,我知道--spek指向spek之前的对象,但是无法找出逻辑behing检查,如果之前指向的是0,那么它的okey要删除,或复制,但为什么?正如我所说,我已经搜索了webb,并找到了一些答案来帮助我理解指针和减法等的功能,更多的是令人困惑的逻辑.
最好的祝福
由于运算符优先,--srep->refCount不是递减srep,而是refCount成员.
因此,代码正在递减refCount,如果它降为0,则可以假定对象的最后一个引用正在被销毁.
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |