none
std::unique_ptr with std::vector RRS feed

  • Question

  • Is this a correct way of using std::unique_ptr with a std::vector?

    std::vector<std::unique_ptr<Monster>> v1;
    		
    std::unique_ptr<Monster> m1(new CookieMonster());
    v1.push_back(std::move(m1));
    std::unique_ptr<Monster> m2(new FartMonster());
    v1.push_back(std::move(m2));
    for(auto it = v1.begin(); it != v1.end(); ++it) {
         std::unique_ptr<Monster> m = (std::unique_ptr<Monster>)std::move(*it);
        m->Intimitade();
    }


    Friday, September 14, 2012 11:42 AM

Answers

  • I would say it's not because the for loop moves all the monsters in the vector to the graveyard, I'm sure you want to be able to "Intimitade" them again later...

    So don't move, do this instead:

        for (auto it = v1.begin(); it != v1.end(); ++it) {
            auto& m = *it;
            m->Intimitade();
        }
    

    Or the shorter:

        for (auto it = v1.begin(); it != v1.end(); ++it) {
            (*it)->Intimitade();
        }
    

    • Marked as answer by Anonymous7520 Friday, September 14, 2012 12:04 PM
    Friday, September 14, 2012 12:01 PM
    Moderator

All replies

  • I would say it's not because the for loop moves all the monsters in the vector to the graveyard, I'm sure you want to be able to "Intimitade" them again later...

    So don't move, do this instead:

        for (auto it = v1.begin(); it != v1.end(); ++it) {
            auto& m = *it;
            m->Intimitade();
        }
    

    Or the shorter:

        for (auto it = v1.begin(); it != v1.end(); ++it) {
            (*it)->Intimitade();
        }
    

    • Marked as answer by Anonymous7520 Friday, September 14, 2012 12:04 PM
    Friday, September 14, 2012 12:01 PM
    Moderator
  • Yes you are right, thanks.
    Friday, September 14, 2012 12:05 PM