我找不到(在关于析构函数调用主题的许多问题中)任何与我的情况完全相同的问题。
当传递的参数是引用时,为什么会调用析构函数?我将注释(主要在 main 中)放在我认为执行输出的代码行下。
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”,所以它一定是因为某些东西超出了范围。但我不认为超出复制赋值函数范围的引用会执行此操作。