嗨,我有一个测试tomarrow,无法弄清楚为什么在检查引用是否为0之前对指针进行减法。我一直在搜索谷歌,但仍然无法弄明白。所以我希望转向你们:)会有所帮助。 最简单的只是向您展示代码,我已经用注释标记了这些行,所以这里是:
这是StringRep类,它有指向它的指针,用于计算指向它的指针
struct StringRep{
int size; // amount of chars incl. EOL \0-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并找到了一些答案来帮助我理解指针和减法等的功能,这更令人困惑。
祝你好运
答案 0 :(得分:8)
由于运算符优先,--srep->refCount
不是递减srep,而是递减refCount成员。
因此,代码正在递减refCount,如果它降为0,则可以假定对象的最后一个引用正在被销毁。
答案 1 :(得分:3)
--srep->refCount
被解析为
--(srep->refCount)
因为前缀减量的优先级低于->
(但是,后缀减少的优先级与->
相同)。始终在自己的代码中使用parens!