Search code examples
c++shared-ptr

Using shared_ptr for different types


I am afraid I think I am missing something here and would like some help. I have searched online (perhaps not very well) but am not finding information which is helping me.

I have a scenario where I want to create three separate vectors all containing shared_ptrs to different types. So I want a a vector containing shared_ptrs of an Enemy object and a vector containing shared_ptrs to an Enemy2 object.

I have successfully used a vector of shared_ptrs before but if I remember correctly, I only ever needed to store the same type so did not have any issues. I am currently trying to implement it like this:

// Defining my vectors
std::vector<std::shared_ptr<Enemy1>> enemyVec1;
std::vector<std::shared_ptr<Enemy2>> enemyVec2;

// Creating new enemy objects and putting in to vector
std::shared_ptr<Enemy1> enemy1(new Enemy());
std::shared_ptr<Enemy2> enemy2(new Enemy());

enemyVec1.push_back(enemy1);
enemyVec2.push_back(enemy2);

Here is the error message:

c:\program files (x86)\microsoft visual studio 10.0\vc\include\memory(1705): error C2664: 'std::tr1::_Ptr_base<_Ty>::_Reset0' : cannot convert parameter 1 from 'Enemy *' to 'Enemy2 *'

I am vaguely familiar with what might be going on here but I am not 100% sure. I am even less sure of how I could go about coding this the "right" way as a lot of examples I look at never seem to cover the use of shared_ptrs for different types.

If I take out all references to Enemy2 class and class and only ever use shared_ptrs for one type exclusively then the code works fine. I thought I knew how shared_ptrs worked but I clearly do not so I need to read up some more about them.

But in the mean time, could someone explain to me what I have done wrong here?

Thanks


Solution

  • You're initialising both enemy1 and enemy2 with new Enemy(). This will only work if Enemy is derived from both Enemy1 and Enemy2. I doubt that's the case, hence the error.

    I believe you should actually be initialising them with instances of the appropriate types Enemy1 and Enemy2. You should also consider using std::make_shared:

    auto enemy1 = std::make_shared<Enemy1>();
    auto enemy2 = std::make_shared<Enemy2>();