簡體   English   中英

使用 STL 時出現分段錯誤

[英]Segmentation Fault while using STL

我在使用 STL 庫時遇到問題。 我附上代碼片段。

// Store a class object in a vector.
#include <iostream>
#include <vector>

using namespace std;

class Parent{
  int id;
public:
  Parent(){};
  Parent(int x){ id=x;}
  virtual ~Parent(){ cout<<"Parent"<<endl;}
  virtual void print3(){cout<<"Printing Parent "<<id;}
};

class Child:public Parent{
  int c;
public:
  Child(int m,int n):Parent(m){
    c=n;
  }
  Child(){c=0;}
  virtual ~Child(){ cout<<"Child"<<endl;}
  virtual void print3(){cout<<"Printing Child  "<<c;}
};

class New_class
{
public:
  New_class(){ 
    tp=new Child(10,20);
  }
  ~New_class(){
    delete tp;
  }
  void check(Parent &tmp){
    tmp.print3();
  }
  void print2(){tp->print3();}
private:
  Parent *tp;

};

class New2{
  vector<New_class> tp2;
public:
  New2(){
    tp2.push_back(New_class());
  }
  ~New2(){
      tp2.clear();
  }
  void print(){ vector<New_class>::iterator it=tp2.begin(); (*it).print2();}
};

int main()
{
  New2 m ;
  m.print();
}

提前致謝。 問候

正如@UncleBens 在評論中所寫, New_class違反了三規則

我個人的建議是不要使用動態分配的屬性......

您的 new2 構造函數將臨時 object 的副本推送到 tp2 向量上。

臨時 object 然后被銷毀並刪除其 tp 指針。 所以向量中的副本現在有一個 tp 指針,它指向已經被釋放的 memory。

您的 New_class 應該實現一個復制構造函數。

您忘記在 New_class 上定義復制構造函數和賦值運算符。 我們經常看到這一點。 這是新手克服的基本障礙,它抓住了大多數人。

當您將項目添加到向量時,復制構造函數被隱式調用,但編譯器生成的版本對於您的 New_class 來說是不夠的,因此您必須自己編寫。

鑒於您的其他代碼,很難為復制構造函數和賦值運算符給出合理的定義,所以我不打算嘗試。 建議您閱讀一本好的 C++ 書籍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM