You would need something like this:
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)); }
Which can be greatly simplified if you get rid of malloc() altogether and use new/new[] or std::make_unique() instead:
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);
Which can then be simplified even further if you use std::vector instead of 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);
memoryget allocated? Can you replaceuint8_t*withunique_ptr<uint8_t[]>?std::vector<uint8_t>memoryStruct. Can you expand on your use case so we can see if you can avoid this altogether?