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

The aligned_ptr alias template is a unique_ptr that uses aligned_delete as the deleter, for destruction and deallocation. This smart pointer type is suitable for managing objects that are allocated with aligned_alloc.

#include <boost/align/aligned_delete.hpp>
#include <memory>

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

The make_aligned function template creates an aligned_ptr for an object allocated with aligned_alloc and constructed with placement new. If allocation fails, it throws an object of std::bad_alloc. If an exception is thrown by the constructor, it uses aligned_free to free allocated memory and will rethrow the exception.

template<class T, class... Args>
inline aligned_ptr<T> make_aligned(Args&&... args)
{
    auto p = boost::alignment::aligned_alloc(alignof(T),
        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;
    }
}

Here make_aligned is used to create an aligned_ptr object for a type which has extended alignment specified.

struct alignas(16) type {
    float data[4];
};

int main()
{
    auto p = make_aligned<type>();
    p->data[0] = 1.0f;
}

The aligned_vector alias template is a vector that uses aligned_allocator as the allocator type, with a configurable minimum alignment. It can be used with types that have an extended alignment or to specify an minimum extended alignment when used with any type.

#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> >;

Here aligned_vector is used to create a vector of integers where each integer object has extended cache alignment.

enum {
    cache_line = 64
};

int main()
{
    aligned_vector<int, cache_line> v(32);
    v[0] = 1;
}


PrevUpHomeNext