shared_ptr causing segfault
I am trying to use shared_ptr with my class but for some reason I get segfault. Maybe I am doing something stupid.
#include <tr1/memory>
#include <iostream>
class Dataset ;
typedef int DataClass;
class Dataset_Impl{
friend class Dataset ;
DataClass *dc;
Dataset_Impl(){dc = new DataClass[10];}
public:
void getSubset(Dataset_Impl* &dObj){
dObj = new Dataset_Impl(); //Causing segfault when using shared_ptr
/*copy subset of 'dc' to dObj->dc and return*/std::cout<<"Copied subset";
}
};
class Dataset{
Dataset_Impl *d;
public:
Dataset (){};
inline void const getSubset(Dataset &dObj) const{d->getSubset(dObj.d);}
};
int main(){
Dataset m1,subset1;std::shared_ptr<Dataset> subset2;
m1.getSubset(su开发者_如何学运维bset1);
m1.getSubset((*subset2)); //Causing segfault
}
You haven't created an object; subset2
is a null pointer. You need to create an object for it to manage:
std::shared_ptr<Dataset> subset2(new Dataset);
For information there is a dedicated function to create a shared_ptr
on a new allocated object , in your case:
std::make_shared<Dataset>()
This will call Dataset()
constructor. If you have a second constructor, let's say Dataset(int)
, you may write std::make_shared<Dataset>(i)
with an integer i.
Your shared_ptr is empty. It does not store a pointer to a Dataset. Use e.g.
std::shared_ptr<Dataset> subset2(new Dataset) ;
you are not creating an object for the shared_ptr variable and trying to access a member variable of pointer. try
std::shared_ptr<Dataset> subset2(new Dataset())
精彩评论