I have a container class like the following. As you can see that all the resources that the class use is allocated statically. There are no dynamically allocated resources in the class. Does such a class need a move constructor or move assignment operator?
template<class T, std::size_t SIZE>
class Stack{
static_assert(SIZE != 0, "Stack capacity cannot be zero!");
public:
/*** Constructors and Destructor ***/
Stack() = default; // Default constructor
Stack(const Stack& copyStack); // Copy constructor
~Stack(); // Destructor
/*** Member Methods ***/
/* .... */
void swap(Stack& swapStack);
private:
/*** Members ***/
std::size_t idxTop{0}; // Index after the top element
T data[SIZE]; // Contained data
};
For the ones who would like to try it out with the actual implementation:
Here's the thing. Your class isn't movable, because it doesn't have dynamically allocated resources. But the resources it contains might. A T
, for instance, might be a std::vector
in some instantiation. That can surely be moved, so you have to make sure that by providing a copy constructor (you forgot to = default;
it btw), the compiler doesn't accidentally disable the default move constructor.
Now, you should be careful about the default move constructor in your case. The problem is that you have an array as a member, and the default move constructor just moves the elements of the array one by one.
Except what happens when the move constructor of one of them throws? You end up with half of the elements moved, and some still in the old array because an exception was thrown. That's no good. Take a look at std::move_if_noexcept
and perhaps try implementing the move constructor to fix this.