STL: Use vector to wrap existing array?
A system call (to retrieve console input events) allocates an array, assigns it to an out parameter, and returns the size of the array. I want to wrap up the data in an STL vector. Is there a way to assign an STL vector a buffer rather than copying the array contents into a new vector and deleting the original array?
~BenDilts( void );
You want to construct your vector with this,
but I don't see a way around deleting the old array.
template<class InputIterator> vector( InputIterator _First, InputIterator _Last );
but I don't see a way around deleting the old array.
Not terribly sanely. I'd recommend using the vector to allocate the array as well. Then you get:
If you really intend to work with pre-existing memory allocated by something else, std::vector is likely unsuitable. The Boost Smart Pointers Library's boost::scoped_array or boost::shared_array may be useful, if your main concern is RAII wrapping.
//old equiv: size_t example( char ** out ) or ( char *& out )size_t example( std::vector< char > & out ) { out.resize( 25 ); //instead of: out = (char *)malloc( 25 ); or similarly ugly non-RAII solution //if you need to fill out using a C-style function: cee_style_function( &(out[0]) ); //and we can of course use STL algorithms: std::fill( out.begin() , out.end() , ' ' ); return out.size();}
If you really intend to work with pre-existing memory allocated by something else, std::vector is likely unsuitable. The Boost Smart Pointers Library's boost::scoped_array or boost::shared_array may be useful, if your main concern is RAII wrapping.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement