0

Minimal example:

#include <iostream>
using namespace std;

class myint{
public:
    int x;
    myint(int x) { this->x = x;}
    ~myint() {cout << "DEL" << endl; }
    myint operator += (int const &y) { this->x += y; return y;}
};


int main() {

    myint i = myint(2);
    i += 3;

}

I'm confused why the object i is destructed twice. How do I avoid this? I will have large objects and will want to optimize the code. I do not want new objects creating when using basic operators.

Jake B.
  • 435
  • 3
  • 13
  • 3
    `myint& operator += (int const &y) { this->x += y; return *this;}` read about operators overload. `operator+=` updates the object. So it should return its modified version. Then you can write things like: `(i += 3) += 5;` – rafix07 Mar 19 '20 at 09:01
  • Read about operator overloading good practices. The general form for this one could be something like : `myint &operator += (int const &y) { this->x += y; return *this;}` – Jean-Baptiste Yunès Mar 19 '20 at 09:05
  • Related: [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – Yksisarvinen Mar 19 '20 at 09:07
  • Thanks! I'm coming from Python, so there are a lot of details for me to catch on. – Jake B. Mar 19 '20 at 09:17

2 Answers2

0

Why are you returning y? You should return *this. Also make the return type myint&.

#include <iostream>
using namespace std;

class myint {
public:
    int x;
    myint(int x) { this->x = x; }
    ~myint() { cout << "DEL" << endl; }
    myint& operator += (int const &y) { this->x += y; return *this; }
};


int main() {

    myint i = myint(2);
    i += 3;
}
FaisalM
  • 724
  • 5
  • 18
0

In your example when you return y; compiler will make implicit conversion and create myint by itself. Take a look Explicit keyword.

So, because of that 2 objects are created insead of one. First object in your main function and second temporary object in your operator +=. When we have two objects we have two descructor calls when main function finishes.

Solution

Use reference and explicit keyword for safety:

#include <iostream>
using namespace std;

class myint {
public:
    int x;
    explicit myint(int x) { this->x = x;}
    ~myint() {cout << "DEL " <<endl; }
    myint& operator += (int const &y) { this->x += y; return *this;}
};

int main() {
    myint i = myint(2);
    i += 3;
}
lukascode
  • 138
  • 1
  • 7