| Home | Libraries | People | FAQ | More

## Examples

### aligned_ptr and make_aligned

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 <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(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;
      }
    }

##### Usage

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

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

### aligned_vector

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 {
      cache_line = 64
    };

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