views:

72

answers:

1

So, I have some code which looks like this:

byte* ar;
foo(ar) // Allocates a new[] byte array for ar 
...
delete[] ar;

To make this safer, I used a scoped_array:

byte* arRaw;
scoped_array<byte> ar;
foo(arRaw);
ar.reset(arRaw);
...
// No delete[]

The question is, Is there any existing way to do this using just the scoped_array, without using a temporary raw array?

I can probably write an in-place "resetter" class, just wondering if the functionality exists and I'm missing it.

Thanks, Dan

A: 

Why can't you just pass a reference to the scoped array to foo and call reset inside of foo?

Alternatively have foo return a boost::shared_array/ptr as follows

boost::shared_array<byte> foo()
{
  boost::shared_array<byte> a (new byte[100]);
  return a;
}

boost::shared_array<byte> ar = foo();

Edit:

Since you cannot change foo how about the following?

byte* rawArray;
foo (rawArray);
boost::scoped_array<byte> array (rawArray);

Alternatively you can overload foo as follows

boost::shared_array<byte> foo()
{
    byte* rawArray;
    foo (rawArray);
    return boost::shared_arry<byte> (rawArray);
}

and then use the overloaded version as follows

boost::shared_array<byte> array = foo();
Stephen Nutt
foo is given, and I don't want to change it. I want to enforce the safety from the scope which is calling foo.
Danra