简体   繁体   中英

c++ std::unique_ptr won't compile in map

I'm currently trying to store a std::unique_ptr in a std::unordered_map, but I get a weird compile error. Relevant code:

#pragma once

#include "Entity.h"

#include <map>
#include <memory>

class EntityManager {
private:
    typedef std::unique_ptr<Entity> EntityPtr;
    typedef std::map<int, EntityPtr> EntityMap;

    EntityMap map;
public:

    /*
    Adds an Entity
    */
    void addEntity(EntityPtr);

    /*
    Removes an Entity by its ID
    */
    void removeEntity(int id) {
        map.erase(id);
    }

    Entity& getById(int id) {
        return *map[id];
    }
};

void EntityManager::addEntity(EntityPtr entity) {
    if (!entity.get()) {
        return;
    }

    map.insert(EntityMap::value_type(entity->getId(), std::move(entity)));
}

This is the compile error:

c:\program files (x86)\microsoft visual studio 12.0\vc\include\tuple(438): error C2280: 'std::unique_ptr<Entity,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function
1>          with
1>          [
1>              _Ty=Entity
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\memory(1486) : see declaration of 'std::unique_ptr<Entity,std::default_delete<_Ty>>::unique_ptr'
1>          with
1>          [
1>              _Ty=Entity
1>          ]
1>          This diagnostic occurred in the compiler generated function 'std::pair<const _Kty,_Ty>::pair(const std::pair<const _Kty,_Ty> &)'
1>          with
1>          [
1>              _Kty=int
1>  ,            _Ty=EntityManager::EntityPtr
1>          ]

The error is because somewhere in the code, map wants to copy a std::pair<int, std::unique_ptr<Entity>> , however there is no copy constructor capable of this, because unique_ptr's are not copy constructable. This is specifically impossible to prevent multiple pointers owning the same memory.

So before std::move, there was no way to use an uncopiable element.

There are some solutions here .

However, in c++11 Map can make use of std::move to work with non-copyable values.

This is done by providing another insert operator, which is overloaded to include this signature:

template< class P > std::pair<iterator,bool> insert( P&& value );

This means an rvalue of a class that can be turned into a value_type can be used as an argument. The old insert is still available:

std::pair<iterator,bool> insert( const value_type& value );

This insert actually copies a value_type, which would cause an error since value_type is not copy constructable.

I think the compiler is selecting the non-templated overload, which causes the compilation error. Because it is not a template, it's failure is an error. On gcc at least, the other insert, which uses std::move, is valid.

Here is test code to see if your compiler is supporting this correctly:

#include <iostream>
#include <memory>
#include <utility>
#include <type_traits>

class Foo {
};

using namespace std;

int main() {
    cout << is_constructible<pair<const int,unique_ptr<Foo> >, pair<const int,unique_ptr<Foo> >& >::value << '\n';
    cout << is_constructible<pair<const int,unique_ptr<Foo> >, pair<const int,unique_ptr<Foo> >&& >::value << '\n';
}

The first line will output 0, because copy construction is invalid. The second line will output 1 since the move construction is valid.

This code:

map.insert(std::move(EntityMap::value_type(entity->getId(), std::move(entity))));

should call the move insert overload.

This code:

map.insert<EntityMap::value_type>(EntityMap::value_type(entity->getId(), std::move(entity))));

Really should call it.

EDIT: the mystery continues, vc returns the incorrect 11 for the test...

Your code works with the following:

int main() {
    EntityManager em;
    em.addEntity(std::unique_ptr<Entity>(new Entity(1)));

    return 0;
}

However this is cumbersome and I'd recommend defining addEntity like so:

void EntityManager::addEntity(Entity *entity) {
    if (entity == nullptr) 
        return;
    }

    map.insert(EntityMap::value_type(entity->getId(),
                std::unique_ptr<Entity>(entity)));
}

and inserting with

em.addEntity(new Entity(...));

Not sure if this solution could help you as well, but I suddenly got the same error on a private std::map<int, std::unique_ptr<SomeType>> data member when I switched from a static library to a dynamic library in Visual Studio 2015 (Update 2) .

Since using template data members together with __declspec(dllexport) produces a warning (at least in MSVC), I resolved that warning by (almost) applying the PIMPL (Private Implementation) idiom. Surprisingly, the C2280 error also disappeared that way.

In your case, it would be:

class EntityManagerPrivate {
public:
    EntityMap map;
};

class EntityManager {
private:
    EntityManagerPrivate* d; // This may NOT be a std::unique_ptr if this class 
                             // shall be ready for being placed into a DLL
public:

    EntityManager();
    ~EntityManager();

   // ...
};

and in the .cpp file:

EntityManager::EntityManager() :
    d( new EntityManagerPrivate() )
{
}

EntityManager::~EntityManager()
{
    delete d;
    d = nullptr;
}

// in all other methods, access map by d->map

Note that for a real PIMPL you would have to move the private class into an own header file which is only referenced by the .cpp. The actual header would only have a forward declaration class EntityManagerPrivate; after the includes. For a real PIMPL , the private class would also have to have implementation in addition to data members.

I had the same issue on VS 2017 with msvc 14.15.26726. According to the compiler error log, things seem to be related to the need for a copy ctor for std::pair<_kT, _T> during instantiation. I don't know why, but one interesting observation (and workaround) for me is to put a declaration of a std::unique_ptr before the declaration of the map, eg:

#pragma once

#include "Entity.h"

#include <map>
#include <memory>

class EntityManager {
private:
    typedef std::unique_ptr<Entity> EntityPtr;
    typedef std::map<int, EntityPtr> EntityMap;
    std::unique_ptr<Entity> aDummyStub; //<-- add this line
    EntityMap map;
//...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM