c – shared_ptr如何破坏对齐

前端之家收集整理的这篇文章主要介绍了c – shared_ptr如何破坏对齐前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_1@我正在阅读关于DirectXMath的文档,并偶然发现了下一篇文章

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.

我不明白shared_ptr如何在对齐策略中做任何改变,它只有一个指针,它不会分配一个对象.

解决方法

你是对的,std :: shared_ptr不会影响对齐.它只接受指向已经分配的对象的指针,因此如果该分配导致对象未对齐,则问题不在于std :: shared_ptr,而是与该分配有关.

但是std :: shared_ptr经常与std :: make_shared一起使用.的std :: make_shared< T>执行单个分配以为std :: shared_ptr控制结构和T实例保留内存.这种分配不是使用任何特定于类的运算符new(并且不应该).如果特定于类的运算符new设置比默认分配器更严格的对齐,那么很容易看到在使用默认分配器时这会如何失败.

原文链接:https://www.f2er.com/c/110623.html

猜你在找的C&C++相关文章