0

I am trying to temporary store a vector of unique pointers and switch them between 2 objects. Here I try to move the ownership of the vector to a temporary vector named oldcards.

std::vector<std::unique_ptr<Building>> oldCards = std::move(player.getBuildingCards()); player.setBuildingCards(std::move(otherPlayer.getBuildingCards())); otherPlayer.setBuildingCards(std::move(oldCards)); 

Player.cpp

std::vector<std::unique_ptr<Building>> const& Player::getBuildingCards() const { return this->buildingCards; } void Player::setBuildingCards(std::vector<std::unique_ptr<Building>> buildingCards) { this->buildingCards = std::move(buildingCards); } 

Player.h

std::vector<std::unique_ptr<Building>> buildingCards;

To conclude: I want to swap 2 vectors, I want player to have the ownership of the vector of otherPlayer and vice versa. However, I get the: attempting to reference a deleted function error. How can I achieve this?

2
  • "and switch them between" - sounds like std::swap. Commented Apr 7, 2019 at 14:29
  • Why all the unnecessary explicit this->? Commented Apr 7, 2019 at 14:30

2 Answers 2

1

I am trying to temporary store a vector of unique pointers and switch them between 2 objects.

Why? Using std::vector::swap would accomplish the same thing with less effort. (Note that this swap most likely should occur within a member function, so there would be no need to use the public accessor functions.)

std::vector<std::unique_ptr<Building>>const& Player::getBuildingCards() const

This returns a const reference. You are not allowed to change something marked const. Moving data out of something counts as changing that something, so moving from getBuildingCards() is not allowed.

void Player::setBuildingCards(std::vector<std::unique_ptr<Building>> buildingCards)

This function takes a copy of a vector as a parameter. Since a vector of unique_ptr cannot be copied, this function signature is DOA. (For the intended purpose, you would want the type of the parameter to be std::vector<std::unique_ptr<Building>>&& to indicate that you will be moving from the parameter.)

Sign up to request clarification or add additional context in comments.

Comments

0

You cannot move from cons T& so copy constructor of oldCards is called which is of course deleted. player.getBuildingCards() cannot change the player instance anyway because you marked it as const.

Cleanest solution (at least according to me) would to implement swapBuildingCards friend function:

class Player { //... std::vector<std::unique_ptr<Building>> buildingCards; friend static void swapBuildingCards(Player& p1, Player &p2) { using std::swap; swap(p1.buildingCards,p2.buildingCards); } }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.