What you are doing here is called assignment. You create a new Myinteger
object with parameter "10"
and assign it to an existing Myinteger
object, obj2
.
What's called here is the assignment operator of obj2
, which if you didn't define yourself, is automatically defined for you by assigning each of the internal fields.
So obj2 = Myinteger("10");
creates a Myinteger
and assigns it to obj2
, and after that it destructs the temporary object in the process. So, the temporary result of Myinteger("10")
is destructed after it has been assigned to obj2
.
The same goes for obj2 = Myinteger("11");
. Finally, obj2
gets destructed when it goes out of scope, at the end of main
.
EDIT: I realized I didn't address what might be the better way to deal with it. Not sure about your specific case, but I'll elaborate on one approach. If you use C++11, you can implement the move constructor and move assignment operator. If you implement those correctly, temporary objects will not assigned using the assignment operator, but by the move assignment operator. In that operator, you can implement it efficiently. There are rules when the move constructor and assignment operator are called implicitly, but it's also possible to use std::move
to force it.
For example, a move assignment of a vector can just transfer the pointer to the underlying array instead of copying the entire array.
Another example is if you have a network connection for each object. You can decide that in the target object, you use the original connection and close the one on the temporary object. If you have an connect
method for the connection and it was not called - then you even haven't wasted any resources yet.
Note that you'll still get 3 constructor and destructor calls, but at least you'll be more efficient dealing with the underlying fields.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…