How should a size-limited stl-like container be implemented?

前端 未结 6 1917
生来不讨喜
生来不讨喜 2020-12-07 04:09

While refactoring, I wanted to change an array where entries are added to an std::vector, but for compatibility (persistency, downgrading,...), it still needs to have an upp

6条回答
  •  情书的邮戳
    2020-12-07 04:23

    You can create a custom allocator (e.g. derived from std::allocator) that refuses to allocate an array larger than a given size.

    Note that you need to call reserve( vector_max ) on the resulting object before adding things to it. I'm filing a defect against the C++ standard, as the requirement should be unnecessary (and it is, on recent versions of GCC).

    template< typename T, size_t N >
    struct limited_alloc : std::allocator< T > {
        size_t max_size() const { return N; }
        typename std::allocator::pointer allocate( size_t n ) {
            if ( n < N ) return std::allocator::allocate( n );
            throw std::length_error( "array too large" );
        }
    
        limited_alloc() {} // silly cruft for standard requirements:
        template< typename T2 >
        limited_alloc( limited_alloc const & ) {}
        template< typename T2 >
        struct rebind { typedef limited_alloc other; };
    };
    
    enum { vector_max = 40 };
    
    template< typename T >
    struct limited_vector {
        typedef std::vector< T, limited_alloc< T, vector_max > > type;
    };
    
    void f() {
        limited_vector< int >::type x;
        x.reserve( vector_max );
        x.assign( vector_max + 1, 3 ); // throws.
    }
    

提交回复
热议问题