c++c++11stlshared-ptrdirectxmath

How can shared_ptr disrupt alignment


I'm reading docs on DirectXMath, and stumbled upon next passage:

As an alternative to enforcing alignment in your C++ class directly by overloading new/delete, you can use the pImpl idiom. If you ensure your Impl class is aligned via __aligned_malloc internally, you can then freely use aligned types within the internal implementation. This is a good option when the 'public' class is a Windows Runtime ref class or intended for use with std::shared_ptr<>, which can otherwise disrupt careful alignment.

I don't understand how shared_ptr can do any change in alignment strategy, it only have a pointer, it doesn't allocate an object.


Solution

  • You're right, std::shared_ptr doesn't affect alignment. It just takes in a pointer to an already allocated object, so if that allocation resulted in a misaligned object, the problem isn't with std::shared_ptr, it's with that allocation.

    But std::shared_ptr is often used with std::make_shared. std::make_shared<T> performs a single allocation to reserve memory both for the std::shared_ptr control structure and the T instance. This allocation isn't done using any class-specific operator new (and shouldn't be). If the class-specific operator new sets up stricter alignment than what the default allocator does, then it's easy to see how this can fail when the default allocator gets used.