I'm looking for a C++ container that's a cross between boost::array, boost::scoped_array and std::vector.
I want an array that's dynamically allocated via new[] (no custom allocators), contained in a type that has a meaningful copy-constructor.
boost::array is fixed-size, and although I don't need to resize anything, I don't know the size of the array at compile time.
boost::scoped_array doesn't have a copy constructor, and that means that I need to manually add one to each and every class using std::copy (my previous copy-paste intensive solution). This is also error prone, since you better make sure when you add a field that you added the correct initializer to the custom copy constructor; i.e. loads of boilerplate.
std::vect开发者_如何转开发or uses some pre-allocation system, and thus does not use operator new[]. This is problematic since it requires custom allocators, and worse, even that's not quite enough since there are some odd corner cases (which I don't fully understand) where return-by-value semantics are concerned that cause problems; I don't want the container to do anything fancy but simply contain a new[]'d array and copy it in it's copy constructor - and preferably overload all the usual suspects to be usable as a collection.
I don't need to resize anything, but the size must be controllable at runtime. Basically, a variant of scoped_array that happens to have a sane copy-constructor (for instance via std::copy) would be fine. Is there a standard collection for something like this?
Basically, I'm looking for a bog-standard dynamically allocated array with value semantics.
Inherit privately from std::vector
, and then adjust appropriately. For example remove resize()
, and perhaps add setsize()
and a bool
flag to determine if the size has been set.
Your copy constructor can invoke the std::vector
copy constructor, and set the flag automatically to prevent further changes.
Doesn't sound hard to write. Something along the lines of this?
template <typename T> my_array {
T* m_ptr;
size_t m_size;
public:
my_array(size_t sz)
: m_ptr(new T[sz])
, m_size(sz)
{}
my_array(const my_array &other)
: m_ptr(new T[other.m_size])
, m_size(other.m_size)
{
std::copy(other.m_ptr, other.m_ptr + other.m_size, m_ptr);
}
~my_array() {
delete[] m_ptr;
}
// ... operator[], etc.
};
Usual disclaimers - this is off the top of my head, has not been compiled or anything.
精彩评论