How is alignment of objects and shared_ptrs calculated?

283 Views Asked by At

Say I have an object managed by a shared pointer: shared_ptr<X>. Lets say my X class is 98 bytes large, with the last data member at byte 97-98 (a char).

Generally speaking the shared ptr contains a raw pointer to my X object and a raw pointer to a reference-counting object, which contains two counters (one strong ref counter and one weak ref counter).

At what address would the reference counting object begin (i.e. the location of the two reference counts)? Would it be immediately following the end of my X class, the 98th byte? Or would there be a particular numerical alignment, say 32-byte aligned and it would be at the 128th byte? What determines the location generally?

Assume make_shared has been used.

1

There are 1 best solutions below

0
On

This is surely an implementation detail.

However there are really only two options, the reference counting stuff can either go before or after the managed T object.

In any case I would assume that the reference counters will be aligned to their natural alignment since having an integer which is not naturally aligned will crash on some platforms and be much, much slower on other platforms.