Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: I need help in pushing a pointer in an vector of shared ptrs  (Read 3204 times)

0 Members and 1 Guest are viewing this topic.

magneonx

  • Full Member
  • ***
  • Posts: 141
    • MSN Messenger - magnumneon04@hotmail.com
    • View Profile
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.

kloffy

  • Newbie
  • *
  • Posts: 21
    • View Profile
Re: I need help in pushing a pointer in an vector of shared ptrs
« Reply #1 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>() );

magneonx

  • Full Member
  • ***
  • Posts: 141
    • MSN Messenger - magnumneon04@hotmail.com
    • View Profile
Re: I need help in pushing a pointer in an vector of shared ptrs
« Reply #2 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?

kloffy

  • Newbie
  • *
  • Posts: 21
    • View Profile
Re: I need help in pushing a pointer in an vector of shared ptrs
« Reply #3 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.