函数副本中的C++双重自由错误

MrM*_*gli 1 c++ double-free

我正在阅读Stroustrup C++ 11的书,我遇到了一个双重免费例外.我知道它释放了两次内存,但我不明白为什么它会发生在一个通过副本传递的函数中:

#include <iostream>

using namespace std;

namespace ALL_Vector { 

  class Vector {
    public:
      // Intitialize elem and sz before the actual function
      Vector(int size) :elem {new double[size]}, sz {size} {};
      ~Vector() {delete[] elem;};

      double& operator[](int i) {
        return elem[i];
      };
      int size() {return sz;};
    private:
      double* elem;
      int sz;
  };


  void print_product(Vector& y) {
    double result {1};

    for (auto x = 0; x < y.size() ; x++){
      if (y[x] > 0) {result *= y[x]; };
    }

    cout << "The product of Vector y is: " << result << ", or so it would appear ;)\n";
  } 

}


/*
  Self test of the Vector class.  
*/

int main(){  
    ALL_Vector::Vector myVector(15);
    cout << "The size of Vector y is: " << myVector.size() << "\n"; 
    myVector[0] = 12;
    myVector[2] = 7;
    myVector[3] = 19;
    myVector[4] = 2;

    ALL_Vector::print_product(myVector);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

print_product()正在使用Vector类并创建一个具有重复内容的新Vector?为什么这会导致双重免费?我假设RIIA在这个例子中以某种方式与Vector :: ~Vector()进行交互,比如竞争条件?

我知道如果我改变它以通过引用传递它的参数它将避免双重释放.我试图通过复制来更好地理解问题.

谢谢!

Ric*_*lly 5

实际上你是在引用print_product myVector,所以一切都很好.
麻烦从传递myVector值开始,因为默认复制构造函数将复制elem指针而不是复制整个数组.
两个ALL_Vector::Vector elem指针都将引用相同的内存存储,因此将被删除两次.
要解决此问题,您必须实现复制构造函数以创建新数组并复制所有元素.