[英]invalid cast from char* to int*
I am trying to use a buffer of char
on the stack as storage for some other type of data. 我试图在堆栈上使用
char
缓冲区作为其他类型数据的存储。
As test I started with the most basic int
but casting pointer of chars to pointer of integer doesn't compile. 作为测试,我从最基本的
int
开始,但是无法编译chars指针到integer指针。
char buf[256];
int* l = static_cast<int*>(buf);
*l = 20;
The error I got is 我得到的错误是
error: invalid static_cast from type ‘char*’ to type ‘int*’
Being these primitive data I was expecting this to work: do you know what is the mechanics behind this specific case? 作为这些原始数据,我希望它能起作用:您知道此特定案例背后的机制是什么?
I sorted out by using reinterpet_cast
but I'd like to use static_cast
as this last should be more fast. 我通过使用
reinterpet_cast
进行了整理,但我想使用static_cast
因为这应该更快。
You will need a reinterpret cast. 您将需要重新解释演员表。 Here's how it works with proper alignment:
正确对齐的工作方式如下:
#include <memory>
std::aligned_storage<20 * sizeof(int), alignof(int)>::type storage;
int * p = reinterpret_cast<int *>(&storage);
for (std::size_t i = 0; i != 20; ++i)
{
::new (p + i) int(i); // or "p[i] = i;"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.