【问题标题】:why subtracting from pointer in this destructor and assignoperator?为什么要从这个析构函数和赋值运算符中的指针中减去?
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 最后一个问题,所以 refCount 在这个实现中应该有一个默认的起始值 1 对吧?
  • @MRK187 我们没有看到默认 String 构造函数的代码,但是是的,它应该使用一些默认值初始化一个新的 StringRep。
  • 其实不行,它是从0开始的,不然就不好用了if (--srep->refCount == 0){
  • 谁能告诉我为什么在向 stringRep 添加新的字符串对象时在 put 函数中减去 refcount ?
  • @MRK187,您通常从 1 开始,因为在创建时您有 1 个参考持有人。请注意,这是一个前缀减量,它是在检查与 0 的相等性之前完成的。
【解决方案2】:
--srep->refCount

被解析为

--(srep->refCount)

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

【讨论】:

  • 谁能告诉我为什么在向stringRep中添加一个新的字符串对象时,为什么在put函数中减去refcount?,至少添加时它没有计数?
猜你喜欢
  • 1970-01-01
  • 2014-06-25
  • 2015-05-01
  • 1970-01-01
  • 2019-11-14
  • 2011-02-03
  • 2011-05-21
  • 2012-11-06
  • 2014-05-29
相关资源
最近更新 更多