Re: dynamically allocated buffers
In article <e2mcbn$5la$1@gavrilo.mtu.ru>, Raider <sraider@yandex.ru>
wrote:
What is the best way to deal with dynamically allocated buffers?
I need smart pointer for the Buffer:
void foo(char *ForceBuffer = NULL)
{
char * Buffer;
if (ForceBuffer) Buffer = ForceBuffer;
else Buffer = new char[size];
SomeCstyleFunctions(Buffer, ...);
// Some C++ code here. May generate exeptions!
if (!ForceBuffer) delete [] Buffer;
}
Choices are:
- auto_ptr<char, array_deleter<char> > // need to write array_deleter
that does delete[]
- boost::scoped_array<char> // need boost library
- vector<char> with resize()
- something else?
Which is the best?
Using std::vector and auto_ptr we get some exception safety.
void foo(char *force_buffer=0)
{
char *buffer = force_buffer;
std::auto_ptr<std::vector<char> > hold_array;
if(!buffer)
{
hold_array = std::auto_ptr<std::vector<char> >
(new std::vector(size));
// set buffer to point to beginning of the new buffer.
buffer = &*hold_array->begin();
}
// use buffer to access_data
}
if an exception occurs or the function exits hold_array's dtor will
be called, it will delete the pointer to vector<char> if it contains
one.
Best is relative:) But this is as safe as your function allows without
writing a special smart pointer [not easy:)] that meets the need
cheaply.
if size is a compile time constant then boost::array<char,size> could
be used instead of vector<char>.
there is no auto_ptr calling delete[].
scoped_array is not copyable in any sense so allocation would occur
whether needed or not.
shared_ptr<char> could be used but the above is cheaper.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]