Felix Dombek
Felix Dombek

Reputation: 14382

Automatically deallocate array?

I'm looking for a way to automatically deallocate an array of wchar_ts – kind of like an autopointer (I'm not really aquainted with std::auto_ptr, but I think it cannot be used for arrays).

The code I have right now is this:

/* volume is of type wstring,
 * hr is of type HRESULT, 
 * VSS_PWSZ equals wchar_t* 
 */

VSS_PWSZ pwszVolume = new wchar_t[volume.size() + 1];
std::copy(volume.begin(), volume.end(), &pwszVolume);
pwszVolume[volume.size()] = 0;

hr = pDiffMgmt->QueryDiffAreasOnVolume(pwszVolume, &pEnumMgmt);

delete[] pwszVolume;
pwszVolume = NULL;

I don't really get why this stupid function cannot take a const wchar_t*, otherwise I could just pass volume.c_str().

So far so good, I think my code solves this problem, but now the memory management is getting more complicated: I would have to duplicate the delete[] code to account for exceptions which might be thrown (and which I do not want to catch at this point.)

Is there a way I can get pwszVolume to be deallocated automatically when the current scope is left?

Upvotes: 2

Views: 1178

Answers (5)

cprogrammer
cprogrammer

Reputation: 5675

You can wrap wchar_t* inside a class, deallocate memory on destruct-or and you have an object that will be automatically deallocated when it loses scope.

Upvotes: 0

James Kanze
James Kanze

Reputation: 154047

As others have said, std::vector is the preferred solution, by far. Otherwise (if e.g. you originally get the pointer from third party software which you cannot modify), there's boost::scoped_array or boost::shared_array.

Upvotes: 1

Praetorian
Praetorian

Reputation: 109289

std::unique_ptr can be used with arrays as follows:

std::unique_ptr<wchar_t[]> pwszVolume(new wchar_t[volume.size() + 1]);

Another option is std::array.

But I agree with Martin's answer that you should just use an std::vector unless you really cannot afford to have the couple of extra pointers that the vector class holds.

Upvotes: 4

Loki Astari
Loki Astari

Reputation: 264739

Use std::vector<wchar_t> it is your basic C++ array (or std::wstring if you want to manipulate it like a string).

std::vector<wchar_t> pwszVolume(volume.begin(), volume.end());
pwszVolume.push_back(0);

hr = pDiffMgmt->QueryDiffAreasOnVolume(&pwszVolume[0], &pEnumMgmt);

The question may be. What does QueryDiffAreasOnVolume() do with the data?
Maybe you do not need to copy it out.

Upvotes: 6

TravisG
TravisG

Reputation: 2373

If you don't want the overhead from std::vector, use boost::array. It is your basic C++ array with static size.

Upvotes: 0

Related Questions