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.
Featured sample: Unique ownership
|
|
Intent
Transfer unique ownership of a dynamically allocated object to another unit of code.
Description
On line 11, we create a std::unique_ptr
which has ownership of a dynamically allocated foo
object (created with the std::make_unique
utility function). Line 12 then demonstrates passing...
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
-
Optional arguments
Allow argument values to be omitted when calling a function.
-
Pass arrays
Pass fixed-size arrays to and from functions.
-
Return multiple values
Return multiple values of different types from a function.
Input streams
-
Read line-by-line
Process the contents of an input stream line-by-line.
-
Read a line of values
Read a sequence of delimited values from a single line of an input stream into a standard container.
-
Validate multiple reads
Ensure that multiple stream reads are successful before using the extracted values.
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
-
Overload operator<<
Write your class type objects to an output stream.
-
Write data in columns
Align data in columns when writing to an output stream.
Random number generation
-
Choose a random element
Choose a random element from a container.
-
Flip a biased coin
Generate a random boolean value according to a bernoulli distribution.
-
Roll a die
Generate a random integer according to a uniform distribution.
Templates
-
Class template SFINAE
Conditionally instantiate a class template depending on the template arguments.
-
Function template SFINAE
Conditionally instantiate a function template depending on the template arguments.
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.