I want to use the vector to collect some generated ints, the number of which I don't know until runtime. However, the interface I have to implement requires returning a native pointer which is supposed to be freed by the caller. The vector is going to be quite large, so, to avoid copying, I do the following:
std::vector<int>* const Collector = new std::vector<int>;
//Several Collector.push_back();s
int* ReturnPointer = Collector->data();
free(Collector);
return ReturnPointer;
The code above is meant to avoid the vector's deconstruction which will free the data pointer that I have to return - and the vector controller itself is freed.
My question is: is this trick safe? Or is there a better solution?
IMPORTANT: The full architecture is out of my control. I'm not allowed to return something other than a native pointer or require the callers to change their calling code. That is, I can't return that vector.
I know that it's bad to free a newed pointer. Then what about doing:
std::vector<int>* const Collector = (std::vector<int>*)malloc(sizeof(std::vector<int>*));
*Collector = std::vector<int>;
//Several Collector.push_back();s
int* ReturnPointer = Collector->data();
free(Collector);
return ReturnPointer;
This time I freed the malloced pointer, is this OK?