你能告诉我为什么这段代码会崩溃吗?

use*_*867 2 c++ crash pointers class function

所以我很好奇以下代码崩溃的原因.将不胜感激.

#include <iostream>
using namespace std;

class temp
{    
  public:

    temp(int i)
    {
        intPtr = new int(i);
    }

    ~temp()
    {
        delete intPtr;
    }

  private:
    int* intPtr;
};

void f (temp fInput)
{
    cout << "f called" << endl;
}

int main()
{
    temp x = 2;
    f(x);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

小智 5

传递x(隐式复制构造函数)时会复制指针,并且在函数返回之前和main返回之前调用析构函数两次,因此内存将被删除两次.

使用std::shared_ptr<int>此处而不是原始int指针(假设您希望行为相同,即int从两个引用相同temp;否则,实现复制构造函数,自己移动构造函数和赋值运算符).

#include <memory>

class temp {    
public:
  temp(int i) : intPtr(std::make_shared<int>(i)) {

  }

private:
  std::shared_ptr<int> intPtr; // reference counting ftw
};
Run Code Online (Sandbox Code Playgroud)


jos*_*mas 5

发生崩溃是因为你的路过x.

f函数范围之后,x将调用destructure并将其删除intPtr.

但是,这将删除仍在范围内的内存main.因此,在return 0调用之后,它将尝试删除已存在的内存,因为您在同一指针上调用了两次delete.

要修复此错误,请更改

void f (temp fInput)
Run Code Online (Sandbox Code Playgroud)

void f (const temp& fInput)
Run Code Online (Sandbox Code Playgroud)

或者,您可以考虑使用std :: shared_ptr.


Ed *_* S. 5

你违反了三法则

您维护一个指针成员,并将该对象的副本传递给该函数f.因此,最终结果是您delete在同一指针上调用两次.