通过引用传递-为什么要调用这个析构函数
Passing by reference - why is this destructor being called?
在析构函数调用主题的许多问题中,我找不到任何与我的情况完全相同的问题。
当传递的参数是引用时,为什么要调用析构函数?我把注释(主要是注释(放在我认为输出执行的代码行下面。
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(——当一个构造的临时对象的生命周期结束时
相关文章:
- 什么时候调用析构函数
- C++-明确何时以及如何调用析构函数
- C++ 防止在映射中放置()时调用析构函数
- 调用析构函数以释放动态分配的内存
- C++:使用方法调用析构函数的顺序是什么?
- 向量推回调用析构函数时调用析构函数
- 如何在调用析构函数时优雅地停止/销毁带有阻塞调用C++线程?
- C++,我应该调用析构函数吗?
- 如何获取有关在 Clang LibTooling 中调用析构函数的信息?
- 当我从 std::vector 中的新放置调用析构函数时会发生什么?
- 为什么这里不调用析构函数
- 在调用 std::bind 的产品后意外调用析构函数
- 为什么在传递给函数而不是构造函数时调用析构函数?
- 如何在C++中调用析构函数
- 为什么为未删除的对象调用析构函数?
- 调用析构函数时出错
- C++ 在不释放内存的情况下调用析构函数
- 为什么在运算符删除中不调用析构函数?
- C++ 调用析构函数后动态模板队列"double free or corruption (out)"
- 在 postOrderDelete 上调用析构函数时引发的异常