我找不到证据来证明/反驳以下代码片段没有设计缺陷,就正确性而言。
template <class Item>
class MyDirtyPool {
public:
template<typename ... Args>
std::size_t add(Args &&... args) {
if (!m_deletedComponentsIndexes.empty()) {
//reuse old block
size_t positionIndex = m_deletedComponentsIndexes.back();
m_deletedComponentsIndexes.pop_back();
void *block = static_cast<void *> (&m_memoryBlock[positionIndex]);
new(block) Item(std::forward<Args>(args) ...);
return positionIndex;
} else {
//not found, add new block
m_memoryBlock.emplace_back();
void *block = static_cast<void *> (&m_memoryBlock.back());
new(block) Item(std::forward<Args>(args) ...);
return m_memoryBlock.size() - 1;
}
}
//...all the other methods omitted
private:
struct Chunk {
char mem[sizeof(Item)]; //is this sane?
};
std::vector<Chunk> m_memoryBlock; //and this one too, safe?
std::deque<std::size_t> m_deletedComponentsIndexes;
};
我关心的是与Chunk有关的所有内容,这里基本上将其用作具有与提供类型相同大小的内存块。
我不想在m_memoryBlock
中明确创建Item对象,因此我需要一种“具有足够空间的内存块”。
我能否确定Chunk将与提供的类型具有相同的大小?请提供一些假设不起作用的示例。
如果我的假设完全错误,我该如何处理?
Chunk
保证至少与Item
的大小相同(可能更大)。 - SergeyAsizeof(Chunk) == sizeof(Item)
是否成立吗? - NathanOliverstd::aligned_storage
代替Chunk
? - CornstalksItem
都有效吗?例如,如果我有一个派生类,那怎么办? - varnie