为什么有两个额外的析构函数调用,因为我只创建了两个对象并使用重载赋值运算符和增量运算符

Why are there two extra calls to destructor as I have created only two objects and using overloaded assignment operator and increment operator

本文关键字:两个 对象 重载 运算符 赋值运算符 因为 析构 函数调用 为什么 创建      更新时间:2023-10-16
#include <iostream>
using namespace std;
class loc{
    int iVAL;
public:
    loc(int i){
        cout<<"inside parameter constructor"<<endl;
        iVAL = i;
    }
    loc(){
        iVAL = 0;
        cout<<"inside default constructor"<<endl;
    }
    loc operator+(loc ob1){
        loc temp;
        temp.iVAL = iVAL + ob1.iVAL;
        return temp;
    }
    void show(){
        cout<<iVAL;
    }
    loc  operator++(){
        cout<<"inside pre increment"<<endl;
        ++iVAL;
        return *this;
    }
    loc operator++(int x){
        cout<<"inside post increment"<<endl;
        iVAL++;
        return *this;
    }
    loc operator=(loc &ob){
        cout<<"inside assignment"<<endl;
        iVAL = ob.iVAL;
        return *this;
    }
    ~loc(){
        cout<<this->iVAL<<endl;
        cout<<"inside loc destructor"<<endl;
    }
};
int main(int argc, char* argv[]){
    loc ob1(10),ob3;
    ob3 = ++ob1;
    return 0;
}

输出:

内部参数构造函数
默认构造函数
内部 内部预增量
内部分配
11
LOC 析构函数内部//对析构函数
的额外调用 11
LOC 析构函数内部//对析构函数
的额外调用 11
LOC 析构函数
内部 11
LOC 析构函数
内部

这是因为

ob3 = ++ob1;

更仔细地查看此代码

loc operator++(({ cout<<"内部预指控"<<p>那么,您可以做些什么来避免此额外副本。您可以通过引用返回

const loc&  operator++(){
   cout<<"inside pre incriment"<<endl;
   ++iVAL;
   return *this; <--- you create a new copy and send it back
}

上面的代码通过引用返回,const 指针是防止其他人修改您的值。

但是,您为预增量编写的代码是错误的它应该在递增之前重新调整值。

所以代码应该是这样的

loc operator++(){
   cout<<"inside pre incriment"<<endl;
   int  temp = iVAL;
   ++iVAL;
   return temp; <--- you create a new copy and send it back
}

在这种情况下,您不能通过引用返回临时变量之间的 temp。