Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2001-09-09 08:00:02


From: "David Abrahams" <david.abrahams_at_[hidden]>
> From: "Peter Dimov" <pdimov_at_[hidden]>
> > From: <rwgk_at_[hidden]>
> > > However, what I am interested in is a vector with two pieces
> > > of member data:
> > > T data_[N];
> > > std::size_t size_; // default constructor: size_ = 0
> > > std::size_t size() const { return size_; }
> > > std::size_t capacity() const { return N; }
> >
> > The C array will default-construct the elements. This is not compatible
> with
> > a std::vector. If you replace it with a char array, we're back to the
> > alignment problem.
>
> It is possible to fix the alignment problem or detect at compile-time that
> we don't know how to fix it, though:
>
> // something like this:
> union everything
> {
> int _int;
> double _double;
> // etc... examples of all POD types
> };
>
> template <std::size_t N>
> struct pod_storage
> {
> everything align; // wasted space
> char data[N]; // construct elements here
> };
>
> template <class T, std::size_t max>
> struct stack_vector
> {
> public: // interface
> //...
> private: // data members
> BOOST_STATIC_ASSERT(sizeof(everything) % boost::alignment_of<T> == 0);
> BOOST_STATIC_ASSERT(boost::alignment_of<T> < sizeof(everything));
> pod_storage<max * sizeof(T)> m_storage;
> };

Yes, I like this, although I'd have preferred

template<class T, std::size_t N> class storage
{
public:
    T * data(); // aligned but not constructed
    T const * data() const;
}

with the ASSERTs in the storage<>.

This kind of thing cries out for compiler support, though.

--
Peter Dimov
Multi Media Ltd.

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk