2

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.

user997112
  • 29,025
  • 43
  • 182
  • 361
  • Huh? The shared pointer (and thus its members) are distinct from the object itself. Their memory locations will be unrelated, in general – Oliver Charlesworth Jun 05 '14 at 21:52
  • @OliCharlesworth not according to this: http://lanzkron.wordpress.com/2012/04/22/make_shared-almost-a-silver-bullet/ – user997112 Jun 05 '14 at 21:52
  • "On the other hand when using make_shared both the tracked object and the reference counting can be allocated together." Take a look at the second diagram too. – user997112 Jun 05 '14 at 21:53
  • Interesting. So make_shared does some magic. Nevertheless, why is the alignment of an internal implementation detail important? – Oliver Charlesworth Jun 05 '14 at 21:55
  • 2
    [Looking at libstdc++](https://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01472_source.html), it seems they use `_Sp_counted_base` with two `_Atomic_word` for the ref counters as a base class for `_Sp_counted_ptr_inplace` which has a data member of a nested class `_Impl` which uses an `__gnu_cxx::__aligned_buffer<_Tp>`. So the memory layout probably looks like this: vptr, strong count, weak count, aligned buffer (assuming empty allocators and the default deleter). – dyp Jun 05 '14 at 23:24
  • @dyp I apologise, I was going through the source code but getting lost! So I guess my question is the memory allocation alignment for the _Sp_counted_base object? Would it be allocated on a word-size (4/8 byte) boundary, or something else? – user997112 Jun 06 '14 at 08:08

1 Answers1

0

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.

Motti
  • 110,860
  • 49
  • 189
  • 262