Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ reference calls 'wrong' destructor

Why does below snippet print:

Constructing Working on this
Constructing working on that
Destructing working on that
Destructing working on that

I would expect "constructing this + that" and "destructing this that".

So the idea here is to have to have a reference to a workingItem and then do something in the destructor if something goes out of scope. It seems that this does not work, and my question is why? Does this cause a memory leak? Also why don’t I get "destructing this" because I did not overwrite a?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I can get this working by making workingItem a pointer, but my question is: is there also a way to get this working by using a ref?

#include <iostream>

class A {
 private:
   std::string str;
 public:
   A(const std::string& s) : str(s) { std::cout << "Constructing "<<s<<std::endl; };
   ~A() { std::cout << "Destructing "<<str<<std::endl; };
};

int main() {
    A a("Working on this");
    A& workingItem=a;
    A a2("working on that");
    workingItem=a2;
}

>Solution :

Implement a operator= to get the full picture:

#include <iostream>

class A {
 private:
   std::string str;
 public:
   A(const std::string& s) : str(s) { std::cout << "Constructing "<<s<<std::endl; };
   ~A() { std::cout << "Destructing "<<str<<std::endl; };
   A& operator=(const A& other){
       std::cout << "assign " << other.str << " to " << str <<"\n";
       str = other.str;
       return *this;
   }
}; 

int main() {
    A a("Working on this");
    A& workingItem=a;
    A a2("working on that");
    workingItem=a2;
}

Output is:

Constructing Working on this
Constructing working on that
assign working on that to Working on this
Destructing working on that
Destructing working on that

You cannot rebind references. This line A& workingItem=a; initializes the reference workingItem to refer to a.

This line is something completely different: workingItem=a2; it assigns a2 to the object refered to by workingItem, and that is a1. It is the same as a1 = a2;. Hence you end up with two identical As that get destroyed when main returns.

In general it is important to be aware of the difference between initialization, T x = y;, and assignment, x = y;.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading