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 protected]

comments powered by Disqus

Featured

  • Microsoft Extends Low-Code Push with Power Fx Programming Language

    "Using formulas that are already familiar to hundreds of millions of users, Power Fx allows a broad range of people to bring skills they already know to low code solutions."

  • Microsoft's Tools to Fight Solorigate Attack Are Now Open Source

    Microsoft open sourced homegrown tools it used to check its systems for code related to the recent massive breach of supply chains that the company has named Solorigate.

  • Microsoft's Lander on Blazor Desktop: 'I Don't See a Grand Unified App Model in the Future'

    For all of the talk of unifying the disparate ecosystem of Microsoft-centric developer tooling -- using one framework for apps of all types on all platforms -- Blazor Desktop is not the answer. There isn't one.

  • Firm Automates Legacy Web Forms-to-ASP.NET Core Conversions

    Migration technology uses the Angular web framework and Progress Kendo UI user interface elements to convert ASP.NET Web Forms client code to HTML and CSS, with application business logic converted automatically to ASP.NET Core.

Upcoming Events