Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) PimplExample1

 

pimpl example 1: Lizard implementation in one file using boost::shared_ptr is a pimpl example.

 

Most lizards remain having the same gender for all their live. Therefore, it is a good idea to make a lizard's gender a const member variable. Problem is, that this makes a lizard class uncopyable. In this example I solve this by making a Lizard contain an opaque pointer to LizardImpl, where a LizardImpl does have a constant gender. Because I want to be able to do a shallow copy on Lizards, I use a boost::shared_ptr. Also note that the code is very similar to a Strategy design pattern.

Technical facts

 

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: ./CppPimplExample1/CppPimplExample1.pro

 

TEMPLATE = app
CONFIG += console
CONFIG -= qt
QMAKE_CXXFLAGS += -std=c++11 -Wall -Wextra -Weffc++ -Werror
SOURCES += main.cpp

 

 

 

 

 

./CppPimplExample1/main.cpp

 

#include <cassert>
#include <memory>

enum class Gender { male, female };

struct Lizard
{
  Lizard(const Gender gender) noexcept;
  Gender GetGender() const noexcept;
  private:
  struct LizardImpl;
  const std::shared_ptr<const LizardImpl> m_impl;
};

struct Lizard::LizardImpl
{
  LizardImpl(const Gender gender) noexcept;
  Gender GetGender() const noexcept;

  private:
  const Gender m_gender;
};

Lizard::Lizard(const Gender gender) noexcept
  : m_impl(std::make_shared<LizardImpl>(gender) )
{

}

Gender Lizard::GetGender() const noexcept
{
  return m_impl->GetGender(); //Forward to implementation
}

Lizard::LizardImpl::LizardImpl(const Gender gender) noexcept
  : m_gender(gender)
{

}

Gender Lizard::LizardImpl::GetGender() const noexcept
{
  return m_gender;
}


int main()
{
  const Lizard male(Gender::male);
  assert(male.GetGender() == Gender::male);
  const Lizard female(Gender::female);
  assert(female.GetGender() == Gender::female);
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml