0

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

Foo Bah
  • 25,660
  • 5
  • 55
  • 79
Danra
  • 9,546
  • 5
  • 59
  • 117

1 Answers1

0

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
  • 3,258
  • 1
  • 21
  • 21
  • 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 Apr 11 '10 at 08:29
  • I like the overload suggestion, it provides more encapsulation. Thanks! – Danra Sep 27 '11 at 18:33