为什么要在这个析构函数和分配运算符中减去指针

why subtracting from pointer in this destructor and assignoperator?

本文关键字:运算符 指针 分配 析构函数 为什么      更新时间:2023-10-16

嗨,我有一个测试,在检查 refcount 是否为 0 之前,无法弄清楚为什么在指针上进行减法。我一直在谷歌上搜索,但仍然无法弄清楚。所以我希望转向你们:)会有所帮助。最简单的太只是向您展示代码,我已经用注释标记了行,所以这里是:

这是类 StringRep,它有指向它的指针,用于计算指向它的指针引用,

struct StringRep{ 
 int size; // amount of chars incl. EOL -tecken 
 char* chars; // Pointer to char 
 int refCount; // Amount of String-variables
}; 

这是使用 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; 
} 

这是我在测试示例问题上的所有信息,我知道 --spek 指向 spek 之前的对象,但无法弄清楚逻辑 behing 检查现在之前指向的内容是否为 0,然后删除或复制它的 okey,但为什么?正如我所说,我已经搜索了webb并找到了一些答案来帮助我理解指针和减法等的功能,它更多的是令人困惑的逻辑。

此致敬意

由于运算符优先级,--srep->refCount不是递减 srep,而是递减 refCount 成员。

因此,代码正在递减 refCount,如果它下降到 0,它可以假定对对象的最后一个引用正在被销毁。

--srep->refCount

解析为

--(srep->refCount)

因为前缀递减的优先级低于->(但是,后缀递减的优先级与 -> 相同)。始终在您自己的代码中使用括号!