C++​Samples

A repository of modern C++ code samples curated by the community.

C++ Samples was launched on 6th April 2015 and the existing samples are still under review. If you notice any mistakes or would like to contribute additional samples, please leave comments or fork the sample repository.

Common Tasks

Classes

  • Non-member non-friend interfaces

    Reduce dependencies on internal class details and improve encapsulation.

  • The PIMPL idiom

    Remove compilation dependencies on internal class implementations and improve compile times.

  • The rule of five

    Safely and efficiently implement RAII to encapsulate the management of dynamically allocated resources.

  • The rule of zero

    Utilise the value semantics of existing types to avoid having to implement custom copy and move operations.

Functions

Input streams

Memory management

  • Shared ownership

    Share ownership of a dynamically allocated object with another unit of code.

  • Unique ownership

    Transfer unique ownership of a dynamically allocated object to another unit of code.

  • Use RAII types

    Avoid manual memory management to improve safety and reduce bugs and memory leaks.

Output streams

Random number generation

Templates

Patterns

Behavioral

  • Observer

    Notify generic observer objects when an event occurs.

Creational

  • Builder

    Separate the complex construction of an object from its representation.

Structural

  • Decorator

    Extend the functionality of a class.

Algorithms

Sorting

  • Bubble sort

    Sort a generic range of elements using the bubble sort algorithm.