SFML community forums

Help => General => Topic started by: magneonx on June 25, 2013, 05:49:21 pm

Title: I need help in pushing a pointer in an vector of shared ptrs
Post by: magneonx on June 25, 2013, 05:49:21 pm
Hello guys! Here is my code snippet and the compiler spew out some error which I cannot resolve

    vector<  shared_ptr< SpriteAssets > > _projectiles;
    _projectiles.push_back( new ProjectileObjects() );
 


How can this be an error???
I do not understand ProjectileObjects is a SpriteAsset.
I have tried replacing ProjectileObjects on the shared_ptr and still I got the same error.
I have made the code simpler because this is the only part I got stuck.

here is the error
main.cpp|83|error: no matching function for call to 'std::vector<std::tr1::shared_ptr<SpriteAssets> >::push_back(ProjectileObjects*)'|
 

I need help.
Title: Re: I need help in pushing a pointer in an vector of shared ptrs
Post by: kloffy on June 25, 2013, 06:05:10 pm
That is because a pointer is not a shared_ptr. In C++11 this will work:

vector<  shared_ptr< SpriteAssets > > _projectiles;
_projectiles.emplace_back( new ProjectileObjects() );

Otherwise, just create a shared_ptr:

vector<  shared_ptr< SpriteAssets > > _projectiles;
_projectiles.push_back( make_shared<ProjectileObjects>() );
Title: Re: I need help in pushing a pointer in an vector of shared ptrs
Post by: magneonx on June 25, 2013, 06:17:56 pm
That was frustrating and thanks for showing me the emplace_back

But I think I stick with the second one. Actually I have made it to work, I realize what scot meyer told me from his book that it is a good practice to make shared_ptr stand alone, thats what I did.

Also on your second one? my ProjectileObjects has parameters how can I make it so with make_shared call?
Title: Re: I need help in pushing a pointer in an vector of shared ptrs
Post by: kloffy on June 25, 2013, 06:36:36 pm
Also on your second one? my ProjectileObjects has parameters how can I make it so with make_shared call?
Simply pass the constructor parameters to the make_shared function. They will be forwarded.