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?
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;.