I'm fairly new to RAII, and I have a class (let's call it A) which contains an std::array which has four std::shared_ptrs to four objects of another user defined class (let's call it B). What I want to do is with a function call, transfer ownership of the four Bs, into a vector that is passes into the function, so that they A can be reset to have four new Bs. My problem is how to do this without destroying any of the Bs.
I don't understand what you want to do exactly but I think you want to move them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class B { ... };
class A {
public:
// 1st: transfer ownership between A-objects
void transfer_to(A& other) {
other.ptrs = std::move(this.ptrs); // move assignment operator is invoked.
}
// 2nd: transfer ownership to outside of the function
std::array<std::shared_ptr<B>, 4> get_ownership() {
return std::array<std::shared_ptr<B>, 4>(std::move(ptr));
}
private:
std::array<std::shared_ptr<B>, 4> ptrs;
};
I'm making tetris. I have a class for each block, and a class for each tetrimino that just carries four blocks down until they land and deals with rotation and stuff like that. What I have to do is transfer the blocks from the tetrimino to the pile of blocks at the bottom, which then frees up the tetrimino so it can be given four new blocks and go back to the top again so it can make them fall down etc
EDIT: Would it work if my array of blocks in the pile at the bottom is initially reset and then the correct member of that array and the shared_ptr in the tetrimino class are swapped with std::swap()?