Search code examples
c++boostoffsetboost-interprocess

How to shrink boost::offset_ptr


I'm using boost::interprocess::offset_ptr<> template class specialization, as a type of several fields in my structure. Unfortunately offset_ptr has a size of an underlying pointer(8 bytes in my case). However I'm convinced, that it will never exceed the max size of 4 bytes integer.

So here comes my question. Can I somehow create 4-bytes range offset_ptr easily, or I will have to cast to and from 4-byte width integer?


Solution

  • offset_ptr with default template parameters is

    static const std::size_t offset_type_alignment = 0;
    
    template <class T, class DifferenceType = std::ptrdiff_t,
    class OffsetType = std::size_t, std::size_t Alignment = offset_type_alignment>
    class offset_ptr;
    

    You can change third parameter of offset_ptr.

    #include <iostream>
    #include <boost/interprocess/offset_ptr.hpp>
    #include <cstdint>
    
    int main()
    {
       using namespace boost::interprocess;
    
       offset_ptr<int, std::ptrdiff_t, std::uint32_t> offs;
       std::cout << sizeof(offs) << std::endl;
    }