How can shared_ptr break alignment

I am reading documents on DirectXMath and stumbled upon the following snippet:

As an alternative to forcing alignment in your C ++ class by directly overloading new / delete, you can use the pImpl idiom. If you class your Impl class is aligned through __aligned_malloc internally, you can then freely use aligned types in your 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 might otherwise violate careful alignment.

I don’t understand how shared_ptr can make any changes to the alignment strategy, it only has a pointer, it does not highlight the object.

+6
source share
1 answer

You are right, std::shared_ptr does not affect alignment. It simply accepts a pointer to an already selected object, so if this distribution led to a displaced object, the problem is not in std::shared_ptr , but in that selection.

But std::shared_ptr often used with std::make_shared . std::make_shared<T> performs one allocation of backup memory for both the std::shared_ptr control structure and the T instance. This distribution is not performed using any operator new for the class (and should not be). If the operator new class for the class sets a lowercase alignment than what the default allocator does, then it's easy to see how this can happen if the default allocator is used.

+10
source

All Articles