Question

GameObject objects are uncopyable. I want to move the object that gameObject is pointing to into the std::map<int,GameObject> gameObjects_ without invoking its copy constructor. This compiler errors with this code, indicating that I am trying to copy the object. What am I doing wrong?

void GameObjectManager::addObject(int id,GameObject* gameObject){
    gameObjects_.insert(std::make_pair(id,std::move(*gameObject)));
}
Was it helpful?

Solution

The code you show is C++11 conforming. Here is a complete demo:

#include <map>

struct GameObject
{
    GameObject(GameObject&&) = default;
};

class GameObjectManager
{
    std::map<int, GameObject> gameObjects_;
public:

    void
    addObject(int id,GameObject* gameObject)
    {
        gameObjects_.insert(std::make_pair(id,std::move(*gameObject)));
    }
};

int
main()
{
}

which compiles using tip-of-trunk clang + libc++. Sorry, I do not have a VC10 workaround.

Update

Adding GameObject(GameObject&&) {} fixed the problem

Ah! If you want to move your objects, you must ensure that they have a move constructor (and usually move assignment operator too).

Here is a very brief tutorial on move semantics:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2027.html

It is somewhat dated, but it still correctly highlights the basics without a lot of reading.

In C++11, sometimes a move constructor and move assignment operator will be automatically generated for you. However VC10 does not implement compiler-supplied move members, so you don't need to worry about that aspect for now.

In your case (deriving from NonCopyable), move members can not be implicitly generated anyway. So you must supply your own. The link to the brief tutorial above describes how to do that, and what is actually going on. In particular, study the clone_ptr example.

OTHER TIPS

Why not std::unqiue_ptr?

typedef std::unique_ptr<GameObject> GameObjectPtr;
typedef std::unordered_map<std::size_t, GameObjectPtr> GameObjectsMap;

then just reference the gameobject_t.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top