Re: Using a std::vector as a variable-length receive buffer
In article <1186936026.342913.89050@k79g2000hse.googlegroups.com>,
irotas <google@irotas.net> wrote:
Thanks everyone for the suggestions. I've written a class that mimics
std::vector but is better suited for my purposes.
If anyone is interested, here's the source code:
http://irotas.fastmail.fm/DynamicBuffer.h
I don't particularly like your solution... It creates a bunch of objects
that may or may not ever get used. I would do something more like this:
This is a stripped down version of a class that I use when I need an
array of objects that are not copy constructible or assignable.
template< typename T >
class Buffer {
T* begin;
T* end;
T* cap;
public:
Buffer(): begin( 0 ), end( 0 ), cap( 0 ) { }
/**
* reinitializes elements (0, s].
* postcondition: size() == s && capacity() >= s
*/
void resize( size_t s ) {
reserve( s );
end = begin + s;
for ( T* inc = begin; inc != end; ++inc )
inc = new ( inc ) T;
}
/**
* invalidates all elements.
* postcondition: size() == 0 && capacity() >= s
*/
void reserve( size_t s ) {
for ( T* inc = begin; inc != end; ++inc )
inc->~T();
end = begin;
if ( s > capacity() ) {
::operator delete( begin );
begin = (T*)::operator new( s * sizeof( T ) );
end = begin;
cap = begin + s;
}
}
T& operator[]( size_t i ) {
assert( i < size() );
return begin[i];
}
const T& operator[]( size_t i ) const {
assert( i < size() );
return begin[i];
}
size_t size() const {
return end - begin;
}
size_t capacity() const {
return cap - begin;
}
};
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]