gpt4 book ai didi

c++ - 可移植的 c++ 对齐?

转载 作者:太空狗 更新时间:2023-10-29 23:41:48 25 4
gpt4 key购买 nike

我想将 Pimpl 惯用法与本地存储惯用法一起应用:


mytype.h

class mytype {
struct Impl;
enum{ storage = 20; }
char m_storage[ storage ];
Impl* PImpl() { return (Impl*)m_storage; }
public:
mytype();
~mytype();
void myMethod();
};

mytype.cpp

#include "mytype.h"
struct mytype::Impl {
int foo;
void doMethod() { foo = (foo-1)*3; };
}

mytype::mytype() {
new (PImpl()) Impl(); // placement new
//check this at compile-time
static_assert( sizeof(Impl) == mytype::storage );
//assert alignment?
}

mytype::~mytype() {
PImpl()->~();
}
void mytype::myMethod() {
PImpl()->doMethod();
}

我对这种方法唯一关心的是 m_storage 的对齐。 char 不能保证以与 int 相同的方式对齐。原子可能有更严格的对齐要求。我正在寻找比 char 数组更好的东西来声明存储,使我能够定义(和断言)对齐值。你知道这样的事情吗?也许 boost 库已经这样做了?

最佳答案

boost::aligned_storage http://www.boost.org/doc/libs/1_43_0/libs/type_traits/doc/html/boost_typetraits/reference/aligned_storage.html应该可以解决问题。

您是否有理由不只是使用普通的 pimpl 方法?

关于c++ - 可移植的 c++ 对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7931694/

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