I am trying out different data structures to learn more about smart pointers. I have created a queue implementation which has push
, pop
, front
, back
and size
functions.
#include <iostream>
#include <memory>
#include <cstddef>
template<typename T>
class Queue
{
std::unique_ptr<T[]> q_ptr;
int front_idx = -1;
int back_idx = -1;
int capacity = 0;
public:
Queue(std::size_t space)
{
q_ptr = std::unique_ptr<T[]>(new T[space]);
capacity = space;
}
void push(T value);
void pop();
T front() const;
T back() const;
std::size_t size() const;
};
template<typename T>
void Queue<T>::push(T value)
{
if(front_idx == -1)
{
front_idx++;
}
if(back_idx - front_idx + 1 == capacity)
{
std::cerr << "Queue full\n";
return;
}
q_ptr[++back_idx] = value;
}
template<typename T>
void Queue<T>::pop()
{
if(front_idx == -1)
{
std::cerr << "Empty queue\n";
return;
}
q_ptr[front_idx++] = T{};
}
template<typename T>
T Queue<T>::front() const
{
return q_ptr[front_idx];
}
template<typename T>
T Queue<T>::back() const
{
return q_ptr[back_idx];
}
template<typename T>
std::size_t Queue<T>::size() const
{
return back_idx - front_idx + 1;
}
int main()
{
Queue<int> q1{20};
q1.pop();
for(int i = 0; i < 23; i++)
{
q1.push(i);
}
std::cout << "Queue size: " << q1.size() << "\n";
std::cout << "Queue front: " << q1.front() << "\n";
std::cout << "Queue back: " << q1.back() << "\n";
q1.pop();
std::cout << "Queue size: " << q1.size() << "\n";
std::cout << "Queue front: " << q1.front() << "\n";
q1.pop();
std::cout << "Queue size: " << q1.size() << "\n";
std::cout << "Queue front: " << q1.front() << "\n";
q1.push(12);
std::cout << "Queue size: " << q1.size() << "\n";
std::cout << "Queue back: " << q1.back() << "\n";
}
The attempt is to use
unique_ptr
as an array similar to a raw pointer. Is the usage and approach correct? Can it be improved?As far as I know, I cannot use
shared_ptr
this way in C++11 or C++14. Is this the best approach withshared_ptr
?