这个对象的析构函数是如何被调用两次的?
How is this object's destructor being called two times?
有人可以解释一下 test1 是如何被销毁 2 次的吗?使用 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;
}
输出:
test2constructor called
test1constructor called
test1 destructor called
test2 destructor called
test1 destructor called
swap
的大致实现如下:
template<typename T>
void swap(T& x, T& y) {
T tmp = std::move(x);
x = std::move(y);
y = std::move(tmp);
}
有一个临时变量tmp
,当它离开swap
的范围时被销毁。
由于一开始由x
初始化,其值为1
,再次赋值给y
时,std::move
不会改变其值值,所以它的值仍然是 1
.
有人可以解释一下 test1 是如何被销毁 2 次的吗?使用 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;
}
输出:
test2constructor called
test1constructor called
test1 destructor called
test2 destructor called
test1 destructor called
swap
的大致实现如下:
template<typename T>
void swap(T& x, T& y) {
T tmp = std::move(x);
x = std::move(y);
y = std::move(tmp);
}
有一个临时变量tmp
,当它离开swap
的范围时被销毁。
由于一开始由x
初始化,其值为1
,再次赋值给y
时,std::move
不会改变其值值,所以它的值仍然是 1
.