通过引用传递-为什么要调用这个析构函数

Passing by reference - why is this destructor being called?

本文关键字:调用 析构函数 为什么 引用      更新时间:2023-10-16

在析构函数调用主题的许多问题中,我找不到任何与我的情况完全相同的问题。

当传递的参数是引用时,为什么要调用析构函数?我把注释(主要是注释(放在我认为输出执行的代码行下面。

struct X { // simple test class
int val;
void out(const std::string& s, int nv)
{
std::cerr << this << "–>" << s << ": " << val << " (" << nv << ")n";
}
// default constructor
X() { 
out("X()", 0); 
val = 0; 
} 
X(int v) { 
val = v; 
out("X(int)", v); 
}
// copy constructor
X(const X& x) {
val = x.val; 
out("X(X&) ", x.val); 
} 
// copy assignment
X& operator=(const X& a)
{
out("X::operator=()", a.val); 
val = a.val; 
return *this;
}
// Destructor
~X() { 
out("~X()", 0); 
}
};
X glob(2); // a global variable
// Output Line 1: X(int): 2 (2)
X copy(X a) { 
return a; 
}

main功能:

int main()
{
X loc{ 4 }; // local variable
// Output Line 2: X(int): 4 (4)
// ^from X(int v) function
X loc2{ loc }; // copy construction
// Output Line 3: X(X&) : 4 (4)
// ^from X(const X& x) function
loc = X{ 5 }; // copy assignment 
// Output Line 4: X(int): 5 (5)
// ^from X(int v) function
// Output Line 5: X::operator=(): 4 (5)
// ^from the '=' operator overload
// Output Line 6: ~X(): 5 (0) - ???
loc2 = copy(loc); // call by value and return 
// Or does Output Line 6 result from here?
.
.
.
}

1( 调用此析构函数是因为loc = X{ 5 }; // copy assignment还是因为:loc2 = copy(loc); // call by value and return之后的行?

2( 为什么要调用它?根据我所读到的,析构函数只在以下情况下调用:

a) names go out of scope
b) program terminates
c) "delete" is used on a pointer to an object

我知道它不是"b"或"c",所以它必须是因为有些东西超出了范围。但我不认为超出复制赋值函数范围的引用可以做到这一点。

您可以看到,在进行复制赋值后不久就会调用析构函数。复制分配完成后,临时(x{5}(将被销毁。

来自标准中关于析构函数的部分:

15.4析构函数

12.析构函数被隐式调用
(12.1(——对于程序终止时具有静态存储持续时间的构造对象,

(12.4(——当一个构造的临时对象的生命周期结束时