【问题标题】:what is the basic use of aligned_storage?对齐存储的基本用途是什么?
【发布时间】:2009-07-04 15:13:47
【问题描述】:

std::tr1::aligned_storage 的基本用法是什么?它可以用作如下数据类型 Foo 的自动内存吗?

   struct Foo{...};
   std::tr1::aligned_storage<sizeof(Foo)
        ,std::tr1::alignment_of<Foo>::value >::type buf;
   Foo* f = new (reinterpret_cast<void*>(&buf)) Foo();
   f->~Foo();

如果是这样,那么在 buf 中存储多个 Foo 怎么样,

    std::tr1::aligned_storage<5*sizeof(Foo)
            ,std::tr1::alignment_of<Foo>::value >::type buf;
    Foo* p = reinterpret_cast<Foo*>(&buf);
    for(int i = 0; i!= 5; ++i,++p)
    {
        Foo* f = new (p) Foo();
    }

它们是有效的程序吗?它还有其他用例吗? 谷歌搜索只提供有关aligned_storage 的文档,但很少涉及它的使用。

【问题讨论】:

    标签: c++


    【解决方案1】:

    嗯,除了您使用reinterpret_cast 之外,我觉得它没问题。 (我不能 100% 确定第二个)。

    reinterpret_cast 的问题在于它不保证转换的结果,只有当你将结果转换回原始类型时,你会得到原始值。所以不能保证强制转换的结果会包含相同的位模式,或者指向相同的地址。

    据我所知,将指针 x 转换为类型 T* 的可移植解决方案是 static_cast&lt;T*&gt;(static_cast&lt;void*&gt;(x)),因为 static_castvoid* 之间的转换保证将指针指向相同的地址。

    但这只是与您的问题无关。 :)

    【讨论】:

    • 这是一个很好的解决方案。 static_cast 到/从 void* 是可以的,但是对于像 static_cast(static_cast(x)) 这样的多个 static_cast 也是如此,其中 x 有一个类型?然后我会将我的所有类型从 X 类型转换为 Y 类型的转换为两个 static_cast 而不是一个 reinterpret_cast 只是为了感觉更安全。 (我使用 GCC 和 MSVC 9 的编译器不会对 reinterpret_cast 造成任何伤害,我不确定其他人是否会这样做。但是,是的,我想更安全:))
    • 是的,我不知道重新解释实际上是一个问题的编译器(我认为他们会让它像你在 C++0x 中所期望的那样工作),但是根据按照标准,这是未定义的行为。 static_cast 技巧应该适用于任何指针类型。
    • template&lt;typename T&gt; T pointer_cast(void* p) { return static_cast&lt;T&gt;(p); }。加上 const 重载版本 (const void* p),将节省一些输入。 Boost有类似的功能,static_pointer_castdynamic_pointer_cast
    • 实际上,在当前以及(草案)C++1x 标准中,不允许 reinterpret_castvoid* 或从 void* 发出(尽管实现允许它)。所以你真的应该使用static_cast。在 C++1x 中,对于标准布局类型,reinterpret_cast&lt;T*&gt;(u) 是根据 static_cast&lt;T*&gt;(static_cast&lt;void*&gt;(u)) 定义的。
    • 既然您判断 reinterpret_cast 有问题,我能问一下为什么吗,以及(技巧问题?)如何将aligned_storage 映射到实际类型?是的,在 C++11 中,reinterpret_cast(对于大多数类型,如果不是所有类型)等价于链式 static_casts。
    猜你喜欢
    • 1970-01-01
    • 2011-05-20
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多