Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.
PrevUpHomeNext

Examples

aligned_ptr and make_aligned
aligned_vector

This example presents an alternative to std::unique_ptr for objects allocated with the aligned allocation function. It is defined simply by providing an alias template which uses std::unique_ptr with our aligned deleter in place of the default std::default_delete deleter. It also presents an alternative to std::make_unique for the creation of these aligned unique pointer objects. It is implemented using our aligned allocation function.

Implementation
#include <boost/align/aligned_alloc.hpp>
#include <boost/align/aligned_delete.hpp>
#include <boost/align/alignment_of.hpp>
#include <memory>

template<class T>
using aligned_ptr = std::unique_ptr<T,
    boost::alignment::aligned_delete>;

template<class T, class... Args>
inline aligned_ptr<T> make_aligned(Args&&... args)
{
    auto p = boost::alignment::aligned_alloc(boost::
        alignment::alignment_of<T>::value, sizeof(T));
    if (!p) {
        throw std::bad_alloc();
    }
    try {
        auto q = ::new(p) T(std::forward<Args>(args)...);
        return aligned_ptr<T>(q);
    } catch (...) {
        boost::alignment::aligned_free(p);
        throw;
    }
}
Usage
struct alignas(16) type {
    float data[4];
};

int main()
{
    auto p = make_aligned<type>();
    p.reset();
}

This example presents an alternative to std::vector that can be used with over-aligned types, and allows specifying a minimum alignment. It is defined simply by providing an alias template which uses std::vector with our aligned allocator.

Implementation
#include <boost/align/aligned_allocator.hpp>
#include <vector>

template<class T, std::size_t Alignment = 1>
using aligned_vector = std::vector<T,
    boost::alignment::aligned_allocator<T, Alignment> >;
Usage
enum
    : std::size_t {
    cache_line = 64
};

int main()
{
    aligned_vector<char, cache_line> v;
    v.emplace_back();
}

PrevUpHomeNext