设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)

Design a class that could only be instantiated by a specific class(by make_unique if possible)

本文关键字:如果 通过 unique make 一个 实例化      更新时间:2023-10-16

我正在实现一个幼稚的内存池,在我的实现中有两个类。

FixedMemoryPool<T>MemoryBlock<T>

FixedMemoryPoolnewElement等用户提供接口,并通过MemoryBlock管理内存。

很明显,任何用户都不应该访问MemoryBlock,它的生命周期完全由FixedMemoryPool管理。对于每个MemoryBlock<T>,它只能由FixedMemoryPool<T>创建。

这是我的实现。

template
<typename T>
class FixedMemoryPool;
template<typename T>
class MemoryBlock
{
friend class FixedMemoryPool<T>;
using blockPtr = unique_ptr<MemoryBlock<T>>;
struct _ConstructorTag { explicit _ConstructorTag() = default; };
public:
MemoryBlock(size_t blockSize, _ConstructorTag)
:data(reinterpret_cast<T*>(operator new(sizeof(T) * blockSize))), allocatedCounter(0), next(nullptr)
{
}
~MemoryBlock()
{
for (size_t i = 0; i != allocatedCounter; i++) {
(data + i) -> ~T();
}
operator delete(data);
}
private:
T* data;
size_t allocatedCounter;
blockPtr next;
template
<typename... Args>
T* construct(Args&&... args)
{
return new (data + (allocatedCounter++)) T(std::forward<Args>(args)...);
}
MemoryBlock(const MemoryBlock&) = delete;
MemoryBlock& operator=(const MemoryBlock&) = delete;
};
template
<typename T>
class FixedMemoryPool 
{
public:
using valueType = T;
FixedMemoryPool(size_t blockSize = 64)
:blockSize(blockSize), head(make_unique<MemoryBlock<T>>(blockSize, MemoryBlock<T>::_ConstructorTag{}))
{
}
FixedMemoryPool(const FixedMemoryPool&) = delete;
FixedMemoryPool& operator=(const FixedMemoryPool&) = delete;
FixedMemoryPool(FixedMemoryPool&& pool) = delete;
FixedMemoryPool& operator=(FixedMemoryPool&&) = delete;
template
<typename... Args>
T* newElement(Args&&... args)
{
//...
}
~FixedMemoryPool() = default;
private:
void expand()
{
// ...
}
size_t blockSize;
unique_ptr<MemoryBlock<T>> head;
};

谢谢你的链接。我知道如何使用私有ctor启用make_unique。然而,我想知道是否有更好的方式来实现我的愿望。

另外,我对operator newoperator delete的用法正确吗?

有点偏离主题,但MemoryBlock没有理由知道类型T

在您的实现中,当您创建一个MemoryBlock然后销毁它时,它最终会调用从未构造过的对象的析构函数,这是未定义的行为。

MemoryBlock应该只知道对象的大小和块中对象的数量。

相关文章: