gpt4 book ai didi

c++ - std::align 的使用问题

转载 作者:太空狗 更新时间:2023-10-29 21:45:59 26 4
gpt4 key购买 nike

考虑以下代码:

#include <memory>
#include <iostream>
#include <cstdio>

using namespace std;

// Visual Studio 2012 don't have alignof as a keyword.
#define alignof(type) __alignof(type)

#define TEST_TYPE int

int main(int, char*[])
{
TEST_TYPE i;
void* pv = &i;
size_t space = 100; // Just some big number.

size_t alignment = alignof(TEST_TYPE);

cout << "Alignment of int: " << alignment << endl;
cout << "Is 'i' aligned: "
<< (size_t(&i) % alignment == 0 ? "true" : "false" )
<< endl;

if ( align(alignment, sizeof(TEST_TYPE), pv, space) )
{
TEST_TYPE* p = reinterpret_cast<TEST_TYPE*>(pv);

cout << "Moved pointer "
<< (size_t(p) - size_t(&i))
<< " bytes"
<< endl;

cout << "Is 'p' aligned: "
<< (size_t(p) % alignment == 0 ? "true" : "false" )
<< endl;
}
else
{
cout << "Can't align 'i'" << endl;
}

return 0;
}

它创建一个(正确对齐的)整数,然后使用整数的地址调用 std::align。我得到的输出是:

int 的对齐方式:4
'i' 是否对齐:true
移动指针 4 个字节
'p'是否对齐:true

表示指针已移动,即使地址已经正确对齐。但是,文档 ( http://en.cppreference.com/w/cpp/memory/align ) 说 “...修改 ptr 以指向此类对齐存储的第一个可能地址...” 但这并不意味着指针应该是不变?

所以我的问题是:如果参数指针已经对齐,那么 std::align 的第三个参数(指针)是否总是会更改为大一大小

编辑

此外,如果指针未更改,则 http://www.cplusplus.com/reference/memory/align/?kw=align 中的示例也不会更改。进入无限循环?

第二次编辑

注意链接已更新,可能出现的问题不再出现。

最佳答案

这看起来像是标准库实现中的一个错误,输出应该是“移动指针 0 字节”,因为 pv 已经对齐,所以第一个正确对齐的地址在 [ pv,pv+100),是pv本身,不是pv+4

虽然它确实在标准中说:

The function updates its ptr and space arguments so that it can be called repeatedly with possibly different alignment and size arguments for the same buffer

我不确定这是在说什么,或者它是否相关。我不这么认为。

关于c++ - std::align 的使用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16305311/

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