如何使用包含唯一指针的成员变量创建一个类,可以复制?

时间:2015-04-21 11:13:48

标签: c++ copy-constructor unique-ptr

我有一个包含地图的类(PlayerCharacter),而地图又包含唯一的指针。我有另一个类(Party),它应该包含这个第一类的多个实例。当我尝试为Party实现一个构造函数时,它接受一个PlayerCharacter的实例并将其复制到向量的第一个元素中,我得到了多个错误(使用g ++),这些错误太长而无法解决这个问题。

我认为错误的产生是因为BaseCharacter和PlayerCharacter由于唯一指针而无法复制。如何为此类实现完整的复制构造函数?

MCVE以下

#include <map>
#include <utility>
#include <memory>
#include <vector>

enum class EQUIPMENT_SLOT {
    HEAD
};
class WeaponItem {};
class ClothingItem{};
class BaseCharacter {
    private:
        std::map<EQUIPMENT_SLOT, std::pair<std::unique_ptr<WeaponItem>, std::unique_ptr<ClothingItem>>> _equipment;
};
class PlayerCharacter : public BaseCharacter {};
class Party {
    private:
        std::vector<PlayerCharacter> _party_members;
    public:
        // Addition of this constructor causes errors to appear
        Party(PlayerCharacter player){
            this->_party_members.clear();
            this->_party_members.push_back(player); // This line is the problem - commenting it out compiles fine
        };
};
int main(){
    return 0;
}

1 个答案:

答案 0 :(得分:2)

如果你在unique_ptr中持有物品,通常意味着你不想复制它们。如果你想复制它们,你必须提供这样做的机制:

struct my_thing {
};

using my_thing_ptr = std::unique_ptr<my_thing>;

struct my_container
{
  my_container() {}

  // the presence of _thing will implicitly delete copy constructor 
  // and copy operator so we need to provide them. 
  // Since we're defining copy operators, these will disable 
  // the automatic move operators so we need to define them too!

  my_container(const my_container& rhs)
  : _thing { rhs._thing ? new thing { *(rhs._thing) } : nullptr }
  {}

  my_container(my_container&& rhs) = default;

  my_container& operator=(const my_container&& rhs) {
    auto tmp = rhs;
    swap(tmp, *this);
    return *this;
  }

  my_container& operator=(my_container&& rhs) = default;

  // and an implementation of swap for good measure
  void swap(my_container& other) noexcept {
    using std::swap;
    swap(_thing, other._thing);
  }


  my_thing_ptr _thing;

};