struct memoryStruct {
uint8_t* memory;
size_t size;
};
struct memoryStructDeleter {
void operator()(memoryStruct* p) const
{
if (p) {
free(p->memory);
free(p);
}
}
};
...
std::unique_ptr<memoryStruct, memoryStructDeleter> m_chunk( static_cast<memoryStruct*>(std::malloc(sizeof(memoryStruct))) );
if (m_chunk) {
m_chunk->size = DesiredSize;
m_chunk->memory = static_cast<uint8_t*>(std::malloc(m_chunk->size));
}
如果你去掉了
malloc()
合用
new
/
new[]
std::make_unique()
相反:
struct memoryStruct {
std::unique_ptr<uint8_t[]> memory;
size_t size;
memoryStruct(size_t asize = 0) : memory(new uint8_t[asize]), size(asize) {}
// or:
// memoryStruct(size_t asize = 0) : memory(std::make_unique<uint8_t[]>(asize)), size(asize) {}
};
...
std::unique_ptr<memoryStruct> m_chunk(new memoryStruct(DesiredSize));
// or:
// std::unique_ptr<memoryStruct> m_chunk = std::make_unique<memoryStruct>(DesiredSize);
如果您使用
std::vector
std::unique_ptr
:
struct memoryStruct {
std::vector<uint8_t> memory;
memoryStruct(size_t size = 0) : memory(size) {}
};
...
std::unique_ptr<memoryStruct> m_chunk(new memoryStruct(DesiredSize));
// or:
// std::unique_ptr<memoryStruct> m_chunk = std::make_unique<memoryStruct>(DesiredSize);