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

  • Mastering AI Development and Building AI Apps with GitHub Copilot

    Two Microsoft experts explain how GitHub Copilot is evolving from a coding assistant into a broader platform for building, customizing and testing AI-powered developer workflows.

  • VS Code 1.123 Adds Agent Session Sync, 1M Context Windows

    Microsoft released Visual Studio Code 1.123 on June 3, adding agent-focused features, larger model context support, integrated browser updates and a new delay for some automatic extension updates.

  • Copilot Billing Shock Hits Developers

    Developer complaints about GitHub Copilot's new usage-based billing model have centered on unexpectedly rapid AI credit consumption, and neither GitHub nor Microsoft has responded directly to the backlash, though they have previously published guidance to lessen model usage costs.

  • Hands On with GitHub Copilot App Technical Preview: Turning a Blazor Issue into a PR

    GitHub's brand-new Copilot desktop app, in technical preview, handled a small Blazor issue from planning through pull request creation, but the hands-on test also showed why developers still need to verify agent work in the running app before merging.

Subscribe on YouTube