Auto pointer for unsigned char array?

I need a class like std :: auto_ptr for the unsigned char * array allocated by the new []. But auto_ptr only calls delete, not delete [], so I cannot use it.

I also need a function that creates and returns an array. I came out with my own implementation in the ArrayDeleter class, which I use, as in this example:

#include <Utils/ArrayDeleter.hxx>

typedef Utils::ArrayDeleter<unsigned char> Bytes;

void f()
{
  // Create array with new
  unsigned char* xBytes = new unsigned char[10];
  // pass array to constructor of ArrayDeleter and
  // wrap it into auto_ptr
  return std::auto_ptr<Bytes>(new Bytes(xBytes));
}

...
// usage of return value
{
  auto_ptr<Bytes> xBytes(f());
}// unsigned char* is destroyed with delete[] in destructor of ArrayDeleter

Is there a more elegant way to solve this problem? (Even using another "popular" library)

+3
source share
4 answers

Boost -, . , std::vector? , , .

+11

, unsigned char * .

std::vector<unsigned char> vec;
.
.
.
legacy_function(&vec[0], vec.size());
+3

std::basic_string<unsigned char>? , , std::vector<unsigned char>?

+2
  • int, ++, . delete[] delete. std::auto_ptr.

  • , , . : , ArrayDeleter, .

:

  • . . .
  • . std::auto_ptr<Bytes>, : Bytes, - . : std::auto_ptr Bytes, .
  • /. , operator new Bytes. , . . .

:

  • If you are talking about the regular type - just use it std::auto_ptr<type>. That should do the job. However, you should check it with your compiler.

  • For complex types: you can create your own wrapper instead std::auto_ptr.

  • Another option: looks like what you did. However, you must get rid of additional memory allocations and indirectness.
-1
source

Source: https://habr.com/ru/post/1742818/


All Articles