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

Algorithms

Classes

  • Non-member non-friend interfaces

    Reduce dependencies on internal class details and improve encapsulation.

  • The PIMPL idiom

    • c++11
    • c++14

    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

  • Optional arguments

    • experimental

    Allow argument values to be omitted when calling a function.

  • Pass arrays

    • c++11
    • experimental

    Pass fixed-size arrays to and from functions.

  • Return multiple values

    • c++11

    Return multiple values of different types from a function.

Input streams

Memory management

  • Shared ownership

    • c++11

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

  • Unique ownership

    • c++11
    • c++14

    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.

  • Weak reference

    Maintain a non-owning reference to a shared dynamically allocated object to break circular dependencies.

Output streams

Random number generation

Ranges

  • Range-based algorithms

    • c++11

    Implement algorithms that can be applied to any generic range of elements.

  • Range iteration

    • c++11

    Iterate over a range of elements without using iterators or indices.

Templates

  • Class template SFINAE

    • c++11

    Conditionally instantiate a class template depending on the template arguments.

  • Function template SFINAE

    • c++11

    Conditionally instantiate a function template depending on the template arguments.

  • Perfect forwarding

    • c++11

    Forward arguments of one function to another as though the wrapped function had been called directly.

Patterns

Behavioral

  • Observer

    • c++11

    Notify generic observer objects when an event occurs.

  • Visitor

    Separate generic algorithms from the elements or structure on which they operate.

Creational

  • Builder

    Separate the complex construction of an object from its representation.

Structural

  • Decorator

    Extend the functionality of a class.