gpt4 book ai didi

c++ - shared_ptr 如何破坏对齐

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:18:34 28 4
gpt4 key购买 nike

我正在阅读有关 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实例。此分配不是使用任何类特定的 operator new 完成的(不应该)。如果类特定operator new设置比默认分配器所做的更严格的对齐,然后很容易看出当使用默认分配器时这会如何失败。

关于c++ - shared_ptr 如何破坏对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31228656/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com