Can someone please explain how test1 is getting destroyed 2 times? Compiled with Visual Studio C 17
class test {
public:
test(int val):val_(val) {
cout << "test" << val_ << "constructor called\n";
}
~test() {
cout << "test" << val_ << " destructor called\n";
}
int val_;
};
int main() {
auto t2 = test(2);
{
auto t1 = test(1);
swap(t1, t2);
}
return 0;
}
Output:
test2constructor called
test1constructor called
test1 destructor called
test2 destructor called
test1 destructor called
CodePudding user response:
The general implementation of swap
is as follows:
template<typename T>
void swap(T& x, T& y) {
T tmp = std::move(x);
x = std::move(y);
y = std::move(tmp);
}
There is a temporary variable tmp
, which is destroyed when it leaves the scope of swap
.
Since it is initialized by x
at the beginning, its value is 1
, and when it is assigned to y
again, std::move
will not change its value, so its value is still 1
.