为什么即使在复制对象时也会检测到双重释放或损坏

Til*_*ngh 1 c++

我在以下代码中检测到glibc,有人可以向我解释一下

#include<iostream>
using namespace std;
class Sample
{
public:
       int *ptr;
       Sample(int i)
       {
           ptr = new int(i);
       }
       void PrintVal()
       {
       cout << "The value is " << *ptr<<endl;
       }
       ~Sample()
       {
           cout<<"CALLED\n";
            delete ptr;
       }
};
void SomeFunc(Sample x)
{
    cout << "Say i am in someFunc " << endl;
    x.PrintVal();
    //cout<<*(s1.ptr)<<endl;
}
int main()
{
Sample s1=10;
cout<<*(s1.ptr)<<endl;
SomeFunc(s1);
cout<<"HERE\n";
cout<<*(s1.ptr)<<endl;
}
Run Code Online (Sandbox Code Playgroud)

在这里调用cout<<*(s1.ptr)<<endl;glib被检测到.我无法理解的是,为什么即使没有为s1调用desructor,引用也会被删除.

sta*_*ust 6

问题是您没有复制构造函数,并且您拥有动态分配的成员数据.

void SomeFunc(Sample x)
Run Code Online (Sandbox Code Playgroud)

创建一个新的副本s1.而xs1ptr旨意是指向同一位置.一旦函数SomeFunc返回该内存被删除(当x被销毁时).

当主要回报s1被破坏时.现在你的析构函数尝试delete一个已经删除但你有double free or corruption错误的内存位置.


适用于您案例的简单复制构造函数

Sample(const Sample& s)
{
    ptr = new int(*(s.ptr));
}
Run Code Online (Sandbox Code Playgroud)

你似乎并没有在这里使用指针和动态分配.但是,如果您必须使用动态分配,请考虑查看Rule of three智能指针.