Reputation: 1
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?
Upvotes: 0
Views: 387
Reputation: 17072
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.)
Upvotes: 1
Reputation: 19223
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);
}
};
Upvotes: 0