Reputation: 77
#include<iostream>
class base{
public:
virtual void run(){};
protected:
~base(){std::cout<<"destructor for base"<<std::endl;};
};
class derived : public base {
public:
void run(){};
~derived(){std::cout<<"destructor for derived"<<std::endl;};
};
void get_type ( std::shared_ptr<base> b ){
b.reset ( new derived );
std::cout<<"end of get_type"<<std::endl;
}
int main(){
std::shared_ptr<base> b;
get_type ( b ) ;
std::cout<<"out of get_type"<<std::endl;
b->run();
}
It compiles okay but I got segmentation fault. I looked into what's happening and the output is
end of get_type destructor for derived destructor for base out of get_type Segmentation fault: 11
It goes into get_type and allocates its type. However, beyond this function scope it automatically destructs the type again. Then, since it cannot find b->run(), it gives seg fault. Anyone knows how to make it work? I can't find similar questions. Sorry if it is possible duplication.
Upvotes: 3
Views: 72
Reputation: 7996
Your get_type()
function receives a copy of the shared_ptr defined in your main
function. It then assigns a value to this copy and returns. When leaving the get_type
function, the copy deallocates its pointer as is normal. Then in your main
function, the initial shared_ptr is still unassigned and obviously you get a segmenation fault when trying to dereference it to call the run
method.
For your algorithm to work you should ask a non-const reference to the shared_ptr in the get_type
function.
PS: As others pointed out, you MUST make the destructor of your base class virtual.
Upvotes: 3