c++ - Aligned allocation of elements in vector
问题描述
I need to have elements in a std::vector
aligned to some given step in memory. For example, in the program as follows:
#include <vector>
#include <iostream>
struct __attribute__((aligned(256))) A
{
};
int main()
{
std::vector<A> as(10);
std::cout << &as[0] << std::endl;
std::cout << &as[1] << std::endl;
}
I would expect that the last two digits in printed numbers will be ‘00’.
In practice, I see that it is true in Visual Studio 2019, and in gcc 8+. But can I be absolutely sure, or is it just a coincidence and some custom allocator in std::vector
(like boost::alignment::aligned_allocator
) is necessary?
解决方案
In practice, I see that it is true in Visual Studio 2019, and in gcc 8+. But can I be absolutely sure, or is it just a coincidence and some custom allocator in
std::vector
(likeboost::alignment::aligned_allocator
) is necessary?
There is no reason to expect that, provided the absence of bugs in the implementation of the respective compiler (which can however be checked on the assembly level, if required).
Since C++11, there is the alignas
-specifier which allows you to enforce the alignment in a standardized way. Consequently, the standard allocator will call operator new
upon calling allocator::allocate()
, to which it will forward the alignment information according to the documentation. Thus, the standard allocator already respects alignment needs, if specified. However, of course if the global operator new
is overloaded by a custom implementation, no such guarantee can be made.
推荐阅读
- javascript - 如何从打字稿文件调用javascript函数
- java - Swagger 客户端问题:服务是否产生不一致的 JSON/XML 或者我做错了什么?
- python - 如何使用jupyter设置python路径
- elasticsearch - Elasticsearch 无痛脚本不使用 if 条件替换嵌套对象字段值
- javascript - 在变量中从 REST API 传递 GET 答案 - React.js
- libreoffice-calc - How can I add quotation marks to a libreoffice calc cell text?
- python - Crawling data faster in python
- python-3.x - 将烧瓶中base64中的图像转换为添加到PDF中
- android - 如何在 listView Kotlin 中获取图像
- windows - 我可以启用组策略以管理员身份启动应用程序吗?