C++ 为什么在这个析构函数和赋值运算符中从指针减法?
嗨,我有一个关于箭头的测试,在检查refcount是否为0之前,我不明白为什么要对指针进行减法。我一直在谷歌上搜索,但还是搞不懂。所以我希望转向你们:)会有所帮助。 EasyIst太简单了,只需向您展示代码,我已经用注释标记了行,因此如下所示: 这是StringRep类,它有指向它的指针,用于计算指向它的pointerrefC++ 为什么在这个析构函数和赋值运算符中从指针减法?,c++,pointers,operator-overloading,destructor,C++,Pointers,Operator Overloading,Destructor,嗨,我有一个关于箭头的测试,在检查refcount是否为0之前,我不明白为什么要对指针进行减法。我一直在谷歌上搜索,但还是搞不懂。所以我希望转向你们:)会有所帮助。 EasyIst太简单了,只需向您展示代码,我已经用注释标记了行,因此如下所示: 这是StringRep类,它有指向它的指针,用于计算指向它的pointerref struct StringRep{ int size; // amount of chars incl. EOL \0-tecken char* chars; //
struct StringRep{
int size; // amount of chars incl. EOL \0-tecken
char* chars; // Pointer to char
int refCount; // Amount of String-variables
};
这是使用StringRep的类字符串
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的逻辑,那么可以删除或复制,但为什么?正如我所说的,我已经搜索了webb,找到了一些答案,帮助我理解指针和减法等的功能,这更多的是让人困惑的逻辑
最好的问候由于运算符的存在,
--srep->refCount
不是递减srep,而是递减refCount成员
因此,代码正在递减refCount,如果它降到0,则可以假定对对象的最后一个引用正在被销毁
--srep->refCount
被解析为
--(srep->refCount)
因为前缀减量的优先级低于
->
(但是,后缀减量的优先级与->
相同)。在您自己的代码中始终使用paren 操作符绑定如下:-(srep->refCount)
这是最后一个问题,所以refCount在这个实现中应该有一个默认的开始值1,对吗?@MRK187我们没有看到默认字符串构造函数的代码,但是是的,它应该用一些默认值初始化一个新的StringRep。实际上不是,它从0开始,或者,如果(--srep->refCount==0),这将不能很好地工作{
有人能告诉我为什么在向stringRep添加新字符串对象时,put函数中的refcount会被减去吗?@MRK187,您通常从1开始,因为在创建时您有一个引用保持器。请注意,这是一个前缀减量,它是在检查与0的相等性之前完成的。有人能告诉我为什么put函数中的refcount是subtra吗在向stringRep?添加新字符串对象时,至少在添加时它没有计数?