Improving C++ Encapsulation with the Pimpl Idiom: Listing 3

my_queue is now backed in a list instead of a primitive array.

/**********************************************
 my_queue.cpp
**********************************************/
#include "my_queue.h"
#include <stdexcept>
#include <algorithm>
#include <utility>
#include <list>

using namespace std;

struct my_queue::queue_impl {
  list<element_t> element_list;

  queue_impl()=default;
};

my_queue::my_queue() : pImpl{new queue_impl{}} {}

my_queue::my_queue(const my_queue& other) : pImpl{new queue_impl{}} {
  for (auto e : other.pImpl->element_list)
    enqueue(e);
}

my_queue::my_queue(my_queue&& other)=default;

size_t my_queue::enqueue(const element_t& e) {
  pImpl->element_list.push_back(e);

  return pImpl->element_list.size();
}

element_t my_queue::dequeue() {
  element_t ret;

  if (pImpl->element_list.empty())
    throw runtime_error("The queue is empty.");

  ret = pImpl->element_list.front();
  pImpl->element_list.pop_front();

  return ret;
}

size_t my_queue::get_lenght() const {
  return pImpl->element_list.size();
}

bool my_queue::is_empty() const {
  return pImpl->element_list.empty();
}

my_queue& my_queue::operator=(const my_queue& other) {
  if (this!=&other) {
    pImpl->element_list.clear();
    for (auto e : other.pImpl->element_list)
      enqueue(e);
  }

  return *this;
}

my_queue& my_queue::operator=(my_queue&& other)=default;

my_queue::~my_queue()=default;

About the Author

Diego Dagum is a software architect and developer with more than 20 years of experience. He can be reached at email@diegodagum.com.