C++什么时候调用析构函数?
When is the destructor called in C++?
我试图理解为什么在以下代码中调用析构函数。
我猜函数 f() 以某种方式触发了析构函数,但我不明白为什么。
#include <iostream>
using namespace std;
class c {
int* p;
public:
c() { p = new int(1); }
void display() { cout << *p << endl; }
~c() { delete p; }
};
void f(c){};
void main() {
c o;
f(o);
o.display();
getchar();
}
输出为-572662307,最后抛出运行时异常:CrtIsValidHeapPointer(block)。调用了析构函数并删除了该特定地址的指针。
f()
的输入参数被取值,所以copy of o
当调用 f(o)
时。 copy 在 f()
退出时超出范围时被破坏。
您的 c
class 未定义 复制构造函数 或 复制赋值运算符,违反了 Rule of 3 。因此 f()
中的 copied c
对象最终将持有与 o
中的 o
对象相同的 p
指针值20=]。当副本被销毁时,它的析构函数释放 int
,在 main()
中留下 o
和一个指向无效内存的悬空指针,随后对 o.display()
的调用将有 未定义的行为。您需要在 c
class:
中实现正确的复制语义
class c {
int* p;
public:
c() { p = new int(1); }
c(const c &src) { p = new int(*(src.p)); }
~c() { delete p; }
c& operator=(const c &rhs) { *p = *(rhs.p); return *this; }
void display() const { cout << *p << endl; }
};
我试图理解为什么在以下代码中调用析构函数。
我猜函数 f() 以某种方式触发了析构函数,但我不明白为什么。
#include <iostream>
using namespace std;
class c {
int* p;
public:
c() { p = new int(1); }
void display() { cout << *p << endl; }
~c() { delete p; }
};
void f(c){};
void main() {
c o;
f(o);
o.display();
getchar();
}
输出为-572662307,最后抛出运行时异常:CrtIsValidHeapPointer(block)。调用了析构函数并删除了该特定地址的指针。
f()
的输入参数被取值,所以copy of o
当调用 f(o)
时。 copy 在 f()
退出时超出范围时被破坏。
您的 c
class 未定义 复制构造函数 或 复制赋值运算符,违反了 Rule of 3 。因此 f()
中的 copied c
对象最终将持有与 o
中的 o
对象相同的 p
指针值20=]。当副本被销毁时,它的析构函数释放 int
,在 main()
中留下 o
和一个指向无效内存的悬空指针,随后对 o.display()
的调用将有 未定义的行为。您需要在 c
class:
class c {
int* p;
public:
c() { p = new int(1); }
c(const c &src) { p = new int(*(src.p)); }
~c() { delete p; }
c& operator=(const c &rhs) { *p = *(rhs.p); return *this; }
void display() const { cout << *p << endl; }
};