C ++中止(核心转储)

时间:2015-11-04 20:33:07

标签: c++ memory-management abort

执行以下程序时出现Aborted(Core dumped)错误。

#include<iostream>
using namespace std;
class Array
{
      int *m_ptr;
      int m_size;
      public:
             Array(int sz)
             {
                       cout<<"constructor\n";
                       m_size = sz;
                       m_ptr = new int[sz];
             }
             ~Array()
             {
                     cout<<"Delete\n";
                     delete[] m_ptr;
             }
             int& operator[] (int j)
             {
                  cout<<"Operation []\n";
                  return m_ptr[j];
             }
             int& operator[] (int j) const
             {
                  cout<<"Operation []\n";
                  return m_ptr[j];
             }
             void copy(const Array& ar)
             {
                  m_size = ar.m_size;
                  m_ptr = new int[m_size];
                  int *ptr = ar.m_ptr;
                  int j;
                  for(j = 0;j < m_size; j++)
                  m_ptr[j] = ptr[j];
             }
             Array(const Array& ar)
             {
                                copy(ar);
             }
             /*Array& operator= (const Array& ar) //Why this function prevents us from Aborted(Core Dumped)
             {
                    delete m_ptr;
                    copy(ar);
                    return *this;
             }*/
             void print()
             {
                  int i;
                  for(i = 0;i < m_size;i++)
                  cout<<m_ptr[i]<<"  ";
                  cout<<endl;
             }
};
int main()
{
    Array a1(10);
    Array a2(5);
    int i;
    for(i = 0;i < 10;i++)
    {
          a1[i] = 1;
          if(i < 5) a2[i] = 2;
    }
    a1.print();
    a2.print();
    a1 = a2;//If I do not copy a2 in a1, the  Aborted(Core dumped) error disappers
    return 0;
}

显然,这是与内存分配有关的问题。我正在阅读的这本书的作者已经创建了函数Array& operator= (const Array& ar),但我不明白这个函数是如何解决这个问题的。我了解到每次使用new分配新对象时都应该使用析构函数。但是,在这个例子中,我有一个析构函数,但如果我不添加有问题的函数,我得到Aborted(Core dumped)。您能解释一下为什么我会收到此错误消息以及该功能如何解决问题?

0 个答案:

没有答案
相关问题