开发者

Segmentation Fault while using STL

I am facing problem using STL library. I am attaching code snippet.

// 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开发者_Go百科.begin(); (*it).print2();}
};

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

Thanks in advance. Regards


As @UncleBens wrote in the comments, New_class violates the rule of three.

My personal advice would be not to use a dynamically allocated attribute...


Your new2 constructor pushes a copy of a temporary object onto the tp2 vector.

The temporary object is then destroyed and deletes its tp pointer. So the copy in the vector now has a tp pointer which points to memory which has already been freed.

Your New_class should implement a copy constructor.


You forgot to define copy constructor and assignment operator on your New_class. We see this all the time. It's a basic hurdle for newbies to get over, and it catches most people.

The copy constructor is being called implicitly when you add the item to the vector, but the compiler generated version isn't adequate for your New_class so you have to write your own.

It's difficult to give sensible definitions for the copy constructor and assignment operator given your other code, so I'm not going to try. Suggest you read up on it in a good C++ book.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜