为什么要在这个析构函数和分配运算符中减去指针
why subtracting from pointer in this destructor and assignoperator?
嗨,我有一个测试,在检查 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)
因为前缀递减的优先级低于->
(但是,后缀递减的优先级与 ->
相同)。始终在您自己的代码中使用括号!
相关文章:
- C++ 带有函数指针的运算符优先级
- 是否允许编译器省略对指针的 &* 运算符的组合调用?
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 重载 ostream << 运算符,指针作为参数,导致输出上的内存地址
- 在一个指令中声明更多指针的运算符优先级
- 为什么在通过引用返回运算符分配时取消引用'this'指针?
- SFINAE - 检测类型 T 是指针、数组还是带有随机访问运算符的容器,以及给定的值类型
- c++:复制、删除和运算符=在原始指针映射中
- 除了调用全局删除运算符之外,删除一个void指针还能做什么呢
- 类重载运算符 '<' 插入指向该对象集的共享指针时不调用
- 使用继承的指针列表复制构造函数或重载运算符=
- delete运算符如何处理c中的指针
- 为指针重载运算符++
- 在分配指向数组内存地址的指针时,为什么不必使用地址运算符?
- 如何从模板类重载创建的指针对象上的运算符?
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 为什么运算符"new"需要指针才能工作?
- C++运算符指针,乘法
- 运算符指针数组的新语法
- 重载运算符(指针)