【发布时间】:2014-02-01 15:49:47
【问题描述】:
嗨,我有一个测试 tomarrow,在检查 refcount 是否为 0 之前无法弄清楚为什么要在指针上进行减法。我一直在谷歌上搜索,但仍然无法弄清楚。所以我希望转向你们:)会有所帮助。 最简单的也只是给你看代码,我已经用cmets标记了这些行,所以这里是:
这是 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 之前的对象,但无法弄清楚检查之前指向的对象是否为 0 的逻辑,然后它的 okey删除或复制,但为什么呢?正如我所说,我已经搜索了 webb 并找到了一些答案来帮助我理解指针和减法等的功能,这更多的是令人困惑的逻辑。
最好的问候
【问题讨论】:
-
运算符绑定如下:
--(srep->refCount)
标签: c++ pointers operator-overloading destructor