I have an api call which populates an array of raw pointers to be used by the caller. This function heap allocates each raw pointer but does not allocate the array.
I cannot change this API function regardless of how bad it is.
Calling the api function code looks something like this:
size_t response_count = api.getResponseCount();
std::vector<Response*> responses(response_count);
api.getResponses(responses.data());
for(auto response : responses) {
// Do some processing with response
delete response;
}
I would like to wrap each response in a unique_ptr such that it is still cleaned up at the end of the loop iteration without having to explicitly call delete. Ideally, this would look something like:
for(std::unique_ptr<Response> response : responses) {
// Do some processing with response
// No need to delete response, it will be cleaned up as it goes out of scope
}
This does not compile because the compiler cannot convert a pointer to a unique_ptr:
error: conversion from ‘Response*’ to non-scalar type ‘std::unique_ptr<Response>’ requested
Is there way to cast each element of the container to a smart pointer in this way, or do I need to explicitly delete the raw pointer?