Search code examples
c++vectorshared-ptr

Vector of shared_ptr gives seg fault when instances in vector accessed


I have a vector of shared_ptr<SomeClass> named allParts.

The code is like below:

void function thisIsWhereItStarts(){
    vector<shared_ptr<SomeClass> > allParts;
    for(i=0;i<N;i++){
        allParts.push_back(function_which_returns_shared_ptr_someclass());
    }

// Then I use this vector as below:  
    for(vector<shared_ptr<SomeClass> >::iterator it = allParts.begin(); it!=allParts.end(); it++){
         (*it)->function_of_SomeClass() ; // THIS GIVES SEGMENTATION FAULT
    }
}

I've used vector of pointers a number of times before, but this is the first time I'm using shared_ptr .

The function which returns the shared_ptr is like this:

shared_ptr<SomeClass> function_which_returns_shared_ptr_someclass(){

    shared_ptr<SomeClass> part(new SomeClass);
    if(part->some_function(some_parameter)){
         return part;
    }else{
         return shared_ptr<SomeClass>();
    }

} 

Solution

  • You push_back even an empty shared_ptr. Then you dereference every shared_ptr in the vector. Dereferencing an empty shared_ptr will fail. Either don't push_back the empty pointers or don't dereference them.