Dan Dan - 1 year ago 61
C++ Question

C++ (not C++11) Best way to release array in very large methods

I have to modify a very large method with many possible execution flows. The modification involves to allocate a char array in the heap using

. I want to be sure that this array is released properly, but I want to avoid the need of do the
in all the possible execution flows. In addition, I want to make something "cleaner" for this purpose to avoid future bugs.

I have thought to alloc the array with
and then wrap it into a local
(but keeping the reference to the raw pointer, since the method uses this reference intensively) and let the wrapper delete the raw pointer when it is out of scope.

Here I attach an example. The purpose of this example is to show the kind of operations that are peformed with the raw pointer.

char *rawPtr = new char[1024];
std::vector wrapper(rawPtr, rawPtr + 1024); // <= Does it assure that rawPtr will be released properly?
for(int i = 0; i < 1024; i++)
rawPtr[i] = ...;

rawPtr += sizeof(...);
rawPtr -= ...;
return ...;

return ...;

So, my question is if I can be sure that the
will be released properly regardless program failures, exceptions, incoming
statements etc.

PD.: I cannot use
, the most similar thing I have to a smart pointer is
and this uses
, not

Answer Source

You can create vector<char> of length 1024 and then use pointer to its first element as rawPtr. It will be no need to call new and delete[] then.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download