This question is different from all of:
Copy constructor calls destructor c++ (unrelated)
c++ Copy constructors and destructors (unrelated)
extraneous calls to copy-constructor and destructor (related but not STL used in my case)
[Why is the destructor of the class called twice?] (Why is the destructor of the class called twice?) (unrelated)
Constructor and destructor Calls (unrelated)
copy constructor,destructor and temporaries (unrelated)
which are suggested by stack overflow.
Say you have this simple code.
#include <iostream>
using namespace std;
class Int {
private:
int i_;
public:
Int(Int &&obj) : i_(obj.i_) { //move constructor
print_address_change_(&obj);
cout << i_ << " moved.\n";
}
Int(const Int &obj) : i_(obj.i_) { //copy constructor
print_address_change_(&obj);
cout << i_ << " copied.\n";
}
Int(int i) : i_(i) {
print_address_();
cout << i_ << " constructed.\n";
}
~Int() {
print_address_();
cout << i_ << " destructed.\n";
}
void print_address_() const {
cout << "(" << this << ") ";
}
void print_address_change_(const Int *p) const {
cout << "(" << p << " -> " << this << ") ";
}
const Int operator * (const Int &rhs) const {
return Int(i_ * rhs.i_);
}
};
int main() {
Int i(3);
Int j(8);
cout << "---\n";
Int k = i * j;
cout << "---\n";
}
The result (by g++ 7.3.0 with default option) is this.
(0x7ffd8e8d11bc) 3 constructed. //i
(0x7ffd8e8d11c0) 8 constructed. //j
---
(0x7ffd8e8d11c4) 24 constructed. //tmp
---
(0x7ffd8e8d11c4) 24 destructed. //k
(0x7ffd8e8d11c0) 8 destructed. //j
(0x7ffd8e8d11bc) 3 destructed. //i
OK. A little strange but you can say copy elision must have occurred. So now with -fno-elide-constructors
option, you get the following result.
(0x7ffd8f7693f8) 3 constructed. //i
(0x7ffd8f7693fc) 8 constructed. //j
---
(0x7ffd8f7693c4) 24 constructed. //tmp
(0x7ffd8f7693c4 -> 0x7ffd8f769404) 24 moved. //tmp -> ??? (WHY?)
(0x7ffd8f7693c4) 24 destructed. //tmp
(0x7ffd8f769404 -> 0x7ffd8f769400) 24 copied. //??? -> k (WHY?)
(0x7ffd8f769404) 24 destructed. //??? (WHY?)
---
(0x7ffd8f769400) 24 destructed. //k
(0x7ffd8f7693fc) 8 destructed. //j
(0x7ffd8f7693f8) 3 destructed. //i
This includes three more lines (which marked as "WHY") than I expected. What is ???
? Could anyone please tell me what happened there?