【问题标题】:Segmentation Fault while using STL使用 STL 时出现分段错误
【发布时间】:2011-08-10 06:43:29
【问题描述】:

我在使用 STL 库时遇到问题。我附上代码sn-p。

// 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();
}

提前致谢。 问候

【问题讨论】:

标签: c++ stl polymorphism segmentation-fault


【解决方案1】:

正如@UncleBens 在 cmets 中所写,New_class 违反了rule of three

我个人的建议是不要使用动态分配的属性...

【讨论】:

    【解决方案2】:

    您的 new2 构造函数将一个临时对象的副本推送到 tp2 向量上。

    临时对象随后被销毁并删除其 tp 指针。所以向量中的副本现在有一个指向已经被释放的内存的 tp 指针。

    你的 New_class 应该实现一个拷贝构造函数。

    【讨论】:

      【解决方案3】:

      您忘记在 New_class 上定义复制构造函数和赋值运算符。我们经常看到这一点。对于新手来说,这是一个基本的障碍,它会抓住大多数人。

      将项目添加到向量时会隐式调用复制构造函数,但编译器生成的版本不适用于您的 New_class,因此您必须自己编写。

      鉴于您的其他代码,很难为复制构造函数和赋值运算符给出合理的定义,所以我不打算尝试。建议您阅读一本好的 C++ 书籍。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-06
        • 2017-08-26
        • 2018-06-18
        • 2019-05-10
        • 2018-02-15
        • 2016-01-15
        • 2011-01-14
        • 2013-01-03
        相关资源
        最近更新 更多