gpt4 book ai didi

c++ - sizeof(atomic) 并不总是等于 sizeof

转载 作者:行者123 更新时间:2023-12-05 08:10:39 24 4
gpt4 key购买 nike

sizeof(atomic<T>)的返回值并不总是等于 sizeof(T) 的返回值,基于 [atomics.types.generic]/p9 中的以下句子:

Note: The representation of an atomic specialization need not have the same size as its corresponding argument type. Specializations should have the same size whenever possible, as this reduces the effort required to port existing code

有时它们是相等的,像这样:

struct A {
char i;
const char padding[3];
int j;
};

A a;
a.i = 1;
a.j = 2;
A b;
b.i = 3;
b.j = 4;
std::atomic<A> A_atomic(a);

sizeof(A_atomic)是 8,sizeof(A)也是8。

A_atomic.compare_exchange_weak(a,b)返回真。

A_atomic.is_always_lock_free返回真。

当我添加 int 时变量,它们是不一样的:

struct A {
char i;
const char padding[3];
int j;
int k;
};

A a;
a.i = 1;
a.j = 2;
A b;
b.i = 3;
b.j = 4;
std::atomic<A> A_atomic(a);

sizeof(A_atomic)是 16,并且 sizeof(A)是 12。

A_atomic.compare_exchange_weak(a,b)返回 false。

A_atomic.is_always_lock_free返回真。

std::atomic<A> 发生了什么当我添加 int

我怎样才能找出两个结构之间的细微差别来对齐内存布局,以确保 CAS 返回 true?

我的环境是:

  • macOSX10.13
  • clang-900.0.37
  • x86_64-apple-darwin18.7.0

更多信息:

我再添加一个 int变量如:

struct A {
char i;
const char padding[3];
int j;
int k;
int h;
}

sizeof(A_atomic)是 16,并且 sizeof(A)是 16。

A_atomic.compare_exchange_weak(a,b)返回真。

A_atomic.is_always_lock_free返回真。

最佳答案

您可以尝试使用 #pragma pack(x)(x 是一个数字)来查看它如何影响大小。你可以看看this .

关于c++ - sizeof(atomic<T>) 并不总是等于 sizeof<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72037530/

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