SOLUTION EDIT:
Undefined behaviour is not the underlying issue here. Check my comment for solution, since I could not post an answer after the question was closed.
I am implementing a simple stack data-structure in C++. The capacity is static and included in the class template argument. Whenever I try to push onto the stack when it is full, I get no loud errors. Instead, the count is set to the number that is pushed onto the stack, and incremented by one.
code:
template <typename T, size_t N>
class stack {
public:
stack() : m_count(0), m_data{ 0 } {}
// --- member functions ---
const size_t& push(const T& value) {
m_data[m_count] = value;
m_count++;
return m_count;
}
T pop() {
m_count--;
T temp = m_data[m_count];
m_data[m_count] = 0;
return temp;
}
T& peek() {
return m_data[m_count - 1];
}
// --- capacity ---
const size_t capacity() const {
return N;
}
const size_t& size() const {
return m_count;
}
const bool empty() const {
return m_count ? false : true;
}
friend bool operator==(const stack& lhs, const stack& rhs);
private:
T m_data[N];
size_t m_count;
};
And running like this in main
:
stack<int, 5> st;
for (size_t i = 0; i < st.capacity(); ++i)
st.push(5);
std::cout << "Size of stack: " << st.size() << std::endl; // 5
std::cout << "Capacity of stack: " << st.capacity() << std::endl; // 5
st.push(93); // No visible error
std::cout << "Size of stack: " << st.size() << std::endl; // 94
std::cout << "Capacity of stack: " << st.capacity() << std::endl; // 5
Does anybody know what is going on here?
Edit: Clarification of question