什么是aligned_storage的基本使用? [英] what is the basic use of aligned_storage?

查看:256
本文介绍了什么是aligned_storage的基本使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: tr1 :: aligned_storage的基本用法是什么?它可以作为一个数据类型的自动内存Foo像下面的一样?

What is the basic usage of std::tr1::aligned_storage ? Can it be used as auto memory for a data type Foo like the one below?

   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的方法如下:

If so, what about storing multiple Foo in the buf like,

    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();
    }

它们是有效的程序吗?还有其他用例吗?
Google搜索只生成关于aligned_storage的文档,但对它的用法很少。

Are they valid programs? Is there any other use case for it ? Google search only yields the documentation about aligned_storage, but very little about the usage of it.

推荐答案

从你使用 reinterpret_cast ,它看起来确定对我。 (我不是100%肯定在第二个)。

Well, apart from your use of reinterpret_cast, it looks ok to me. (I'm not 100% sure on the second one).

reinterpret_cast 的问题是,不保证铸造的结果,只有如果你把结果恢复到原来的类型,你得到的原始值。因此,不能保证转换的结果将包含相同的位模式或指向相同的地址。

The problem with reinterpret_cast is that it makes no guarantees about the result of the cast, only that if you cast the result back to the original type, you get the original value. So there is no guarantee that the result of the cast will contain the same bit pattern, or point to the same address.

据我所知,一个便携式解决方案将指针x转换为类型T *是 static_cast (static_cast (x)),因为 static_cast void * 将保证将指针指向同一个地址。

As far as I know, a portable solution for casting a pointer x to a type T* is static_cast<T*>(static_cast<void*>(x)), since static_cast to and from void* is guaranteed to turn a pointer to the same address.

但这只是与你的问题相切。 :)

But that's only tangentially related to your question. :)

这篇关于什么是aligned_storage的基本使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆