【发布时间】:2020-02-29 06:47:06
【问题描述】:
class Pair {
public:
int *pa,*pb;
Pair(int a, int b)
{
pa = new int(a);
pb = new int(b);
}
Pair(const Pair& other) {
int* pc = new int(*other.pa);
int* pd = new int(*other.pb);
}
~Pair() {
delete pa;
delete pb;
}
};
在这个程序中,编译器产生了一个分段错误(核心转储),在完全删除析构函数之后,我们可以让程序运行而没有任何错误,那么任何人都可以帮我解决这个问题吗? 即使在参数化构造函数中,我也初始化了指针,编译器会发出警告,指出点 pa 和 pb 未初始化。
【问题讨论】:
-
这段代码看起来不错。您需要提供一个最小的可重现错误示例(如何使用 Pair 对象)
-
在复制构造函数中,您不会初始化成员变量(您声明了 2 个新的局部变量
pc和pd)。阅读副本,请发布minimal reproducible example,其中应包含足够的代码来重现问题。 -
您的复制构造函数没有设置当前实例的 pa & pb。它正在泄漏/立即丢弃它分配的内存。您还缺少复制分配运算符。
-
你在这里做什么? ``` Pair(const Pair& other) { int* pc = new int(other.pa); int pd = new int(*other.pb); } ```
标签: c++ destructor copy-constructor