Pimple
- “Pointer to implementation” or “pImpl” is a C++ programming technique that removes implementation details of a class from its object representation by placing them in a separate class, accessed through an opaque pointer
CRTP
- The curiously recurring template pattern
- An idiom in which a class
Xderives from a class templateY, taking a template parameterZ, whereYis instantiated with Z = X - General form
// The Curiously Recurring Template Pattern (CRTP)
template
class Base
{
// methods within Base can use template to access members of Derived
};
class Derived : public Base
{
// …
};
- Example
```C++
template <typename T>
struct counter
{
static inline int objects_created = 0;
static inline int objects_alive = 0;
counter()
{
++objects_created;
++objects_alive;
}
counter(const counter&)
{
++objects_created;
++objects_alive;
}
protected:
~counter() // objects should never be removed through pointers of this type
{
--objects_alive;
}
};
class X : counter<X>
{
// ...
};
class Y : counter<Y>
{
// ...
};
RAII
- Resource Acquisition Is Initialization is a C++ programming technique which binds the life cycle of a resource that must be acquired before use to the lifetime of an object.
- RAII guarantees that the resource is available to any function that may access the object
- It also guarantees that all resources are released when the lifetime of their controlling object ends, in reverse order of acquisition
- Only one object can own a resource instance at a time
[std::mutex](http://en.cppreference.com/w/cpp/thread/mutex) m;
void bad()
{
m.lock(); // acquire the mutex
f(); // if f() throws an exception, the mutex is never released
if(!everything_ok()) return; // early return, the mutex is never released
m.unlock(); // if bad() reaches this statement, the mutex is released
}
void good()
{
[std::lock_guard](http://en.cppreference.com/w/cpp/thread/lock_guard)<[std::mutex](http://en.cppreference.com/w/cpp/thread/mutex)> lk(m); // RAII class: mutex acquisition is initialization
f(); // if f() throws an exception, the mutex is released
if(!everything_ok()) return; // early return, the mutex is released
} // if good() returns normally, the mutex is releasedSFINAE
Copy-and-Swap
Info