2 ms·
auto* is just to indicate to the reader that your_malloc for sure returns a raw pointer and not some RAII type already. std::vector::push_back can throw an exc
by jcelerier 4y ago
auto* is just to indicate to the reader that your_malloc for sure returns a raw pointer and not some RAII type already.
std::vector::push_back can throw an exception, if for instance you just allocated 2 gigabytes of memory before and it does not have space to reallocate its internal storage:
std::vector<int> allocation_counts;
auto get_mem(int n) {
auto* memory = your_malloc(n);
// if this throws: the function exits there and "memory" is lost forever
allocation_counts.push_back(n);
return memory;
}
A simple way to "RAII-fy" it would be, assuming a `your_free`:
// Typedef this somewhere
using your_ptr = std::unique_ptr<void, decltype([] (auto p) { your_free(p); })>;
auto get_mem(int n) {
// encapsulate in your_ptr
auto memory = your_ptr{your_malloc(n)};
// if this throws: memory's destructor is called which frees the memory
allocation_counts.push_back(n);
return memory;
}
Or if you want your custom RAII type for some reason:
// memory.h or something
struct mem {
mem() = default;
// copy is not meaningful here
mem(const mem&) = delete;
mem& operator=(const mem&) = delete;
// move
mem(mem&& other): ptr{std::exchange(other.ptr, nullptr)} { }
mem& operator=(mem&& other) { ptr = std::exchange(other.ptr, nullptr); return *this; }
// allocation & deallocation
explicit mem(int n): ptr{your_malloc(n)} { }
~mem() { your_free(ptr); }
void* ptr{};
};
// your code
std::vector<int> allocation_counts;
auto get_mem(int n) {
auto memory = mem{n};
// if this throws: mem's destructor is called which frees the memory
allocation_counts.push_back(n);
return memory;
}