Search code examples
c++destructorpost-increment

Class object deleting after post increment


I have a Weather class. So let's say I create an object of that class let's say Weather object; after that I have created pre and post increments to manipulate the temperature of that weather. So when I do ++object; the temperature increments by one perfectly, but when I do object++; the destructor is called, my pointer is deleted and my temperature then becomes random numbers. My question is, why in the world does the pre increment work, but after post incrementing the destructor is being called on that object? This is my WORKING pre increment:

Weather &Weather::operator++() {
    ++ptr->airTemperature;
    return *this;
}

And this is the NOT WORKING post increment:

Weather Weather::operator++(int) {
    Weather temp = *this;
    ++ptr->airTemperature;
    return temp;
}

As I understand pre increment returns itself and the post increment returns a copy, so I did that, but what could cause the issue?


Solution

  • Try something like this and you can avoid all copy constructors and destructors.

    class Temp {
       double airTemperature;
    };
    
    class Weather {
    
        public:
    
        Weather(std::shared_ptr<Temp> tempPtr)
        : ptr(tempPtr){}
    
        std::shared_ptr<Temp> ptr;
    
        Weather Weather::operator++(int) {
            Weather temp = *this;
            ++ptr->airTemperature;
            return temp;
        }
    
        Weather &Weather::operator++() {
            ++ptr->airTemperature;
            return *this;
        }
    };
    

    Of course consider if you really need a pointer to Temp. Perhaps you should be just doing this.

    class Weather {
    
        public:
    
        Weather(Temp temp)
        : temp(temp){}
    
        Temp ptr;
    
        Weather Weather::operator++(int) {
            Weather temp = *this;
            ++temp.airTemperature;
            return temp;
        }
    
        Weather &Weather::operator++() {
            ++temp.airTemperature;
            return *this;
        }
    };