scoped_array


Header: "boost/scoped_array.hpp"

The need for dynamically allocated arrays is usually best handled by std:: vector, but there are two cases when it makes good sense to use arrays: for optimization, as there is some overhead in size and speed for vector; and for expression of intent, making it clear that bounds are fixed.[5] Dynamically allocated arrays are exposed to the same dangers as ordinary pointers, with the added (and all too common) mistake of invoking the delete operator instead of the delete[] operator. I've seen that mistake in places one could hardly imagine, such as in widely used, proprietary container classes! scoped_array does for arrays what scoped_ptr does for pointers to single objects: It deletes the memory. The difference is that scoped_array does it using the delete[] operator.

[5] These are not clear-cut advantages. Indeed, it is usually best to use std::vector until performance measurements suggest the benefits of scoped_array are warranted.

The reason that scoped_array is a separate class rather than being a specialization of scoped_ptr is because it is not possible to distinguish between pointers to single objects and pointers to arrays using metaprogramming techniques. Despite efforts to make that distinction, no one has found a reliable way to do that because arrays decay so easily into pointers that carry no type information indicating that they point to arrays. As a result, the onus is on you to use scoped_array rather than scoped_ptr, just as you must otherwise choose to use the delete[] operator rather than the delete operator. The benefits are that scoped_array handles deletion for you, and that scoped_array conveys that we are dealing with an array, whereas a raw pointer doesn't.

scoped_array is very similar to scoped_ptr, with the differences that it provides operator[] to mimic a raw array.

scoped_array is a superior alternative to ordinary, dynamically allocated arrays. It handles lifetime management of dynamically allocated arrays, similar to how scoped_ptr manages lifetime for pointers to objects. Remember though, in most cases, std::vector is preferable as it is more flexible and powerful. When you need to clearly state that the size of the array is constant, use scoped_array rather than std::vector.



    Beyond the C++ Standard Library(c) An Introduction to Boost
    Beyond the C++ Standard Library: An Introduction to Boost
    ISBN: 0321133544
    EAN: 2147483647
    Year: 2006
    Pages: 125

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net