3

以下のコードは関数 make_vector() です。ベクトルを作成し、呼び出し元に返します。使用するベクターのアロケーターを指定できるようにしたいのですが、デフォルトでデフォルトの std::allocator を使用します。これは、状況によってはデフォルトのアロケータで十分な場合もあれば、事前に定義されたメモリ プールから割り当てる必要がある場合もあるためです。

最も近いのは make_vector2() 関数テンプレートです。std::allocator で動作しますが、'arena' 引数をカスタム アロケータに渡す方法がわかりません。

この動作する c++11 の例でよりよく説明されることを願っています。

#include <malloc.h>
#include <cinttypes>
#include <cstddef>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <vector>

namespace mem
{
    // Memory arena to allocate from.
    enum class ARENA
    {
        TEXTURES,
        FONTS,
        SCRIPTS
    };

    // Allocate block from specific arena.
    void *malloc( const std::size_t size, const ARENA arena )
    {
        return std::malloc( size /*, arena */ );
    }

    // Free block from specific arena.
    void free( void *ptr, const ARENA arena )
    {
        std::free( ptr /*, arena */ );
    }


    // The allocator - forward declaration.
    // Not derived from std::allocator - should it be?
    // Based on code from here:
    // http://drdobbs.com/184403759?pgno=2
    template<typename T> class allocator;

    // Specialised for void.
    template<> class allocator<void>
    {
        public:
            typedef std::size_t size_type;
            typedef ptrdiff_t difference_type;
            typedef void* pointer;
            typedef const void* const_pointer;
            typedef void value_type;

            template<typename U> struct rebind
            {
                typedef allocator<U> other;
            };
    };


    template<typename T> class allocator
    {
        public:
            typedef std::size_t size_type;
            typedef std::ptrdiff_t difference_type;
            typedef T* pointer;
            typedef const T* const_pointer;
            typedef T& reference;
            typedef const T& const_reference;
            typedef T value_type;

            template<typename U> struct rebind
            {
                 typedef allocator<U> other;
            };

            allocator( ARENA arena ) noexcept :
                arena_( arena )
            {}

            ~allocator() noexcept
            {}

            pointer address( reference x ) const
            {
                    return &x;
            }

            const_pointer address( const_reference x ) const
            {
                return &x;
            }

            pointer allocate( size_type n, allocator<void>::const_pointer hint = 0 )
            {
                void *p = mem::malloc( n * sizeof( T ), arena_ );
                if ( p == nullptr )
                {
                        throw std::bad_alloc();
                }
                return static_cast<pointer>( p );
            }

            void deallocate( pointer p, size_type n )
            {
                mem::free( p, arena_ );
            }

            size_type max_size() const noexcept
            {
                return std::numeric_limits<std::size_t>::max() / sizeof( T );
            }

            void construct( pointer p, const T& val )
            {
                new (p) T(val);
            }

            void destroy( pointer p )
            {
                p->~T();
            }

            allocator( const allocator& src ) noexcept
            {
                arena_ = src.arena_;
            }

            ARENA arena_;
    };
} // namespace mem

template<class T1, class T2> bool operator==( const mem::allocator<T1> &alloc1, const mem::allocator<T2> &alloc2 ) noexcept
{
    return alloc1.arena_ == alloc2.arena_;
}

template<class T1, class T2> bool operator!=( const mem::allocator<T1> &alloc1, const mem::allocator<T2> &alloc2 ) noexcept
{
    if alloc1.arena_ != alloc2.arena_;
}

// How do I allow the custom allocator to be passed? Function parameter? Template?
std::vector<uint8_t> make_vector()
{
    std::vector<uint8_t> vec;
    // Do stuff with the vector
    return vec;
}

// This template function seems to work with std::allocator
template< typename T > std::vector<uint8_t,T> make_vector2()
{
    std::vector<uint8_t,T> vec;
    // Do stuff with the vector.
    return vec;
}

int main( int argc, char **argv )
{
    // vec1 - Allocates from TEXTURES arena
    // See the C++11 FAQ by  Bjarne Stroustrup here:
    // http://www2.research.att.com/~bs/C++0xFAQ.html#scoped-allocator
    std::vector<uint8_t, mem::allocator<uint8_t>> vec1( mem::allocator<uint8_t>{mem::ARENA::TEXTURES} );

    // vec2 - Make the vector using the default allocator.
    auto vec2 = make_vector2< std::allocator<uint8_t> >();

    return 0;
}

main() では、割り当てに TEXTURES アリーナを使用するために vec1 が作成されます。使用するアリーナは、アロケーターのコンストラクターに渡されます。Vec2 は make_vector2() テンプレート関数によって作成され、std::allocator を使用します。

Q: make_vector() 関数を定義して、std::allocator または上記のカスタム プール アロケーターを使用するベクターを作成するにはどうすればよいですか?

4

3 に答える 3

6

C++11 では、関数テンプレートはデフォルトのテンプレート引数を持つことができます:

template<class T, class Alloc = std::allocator<T>>
std::vector<T, Alloc> make_vector(Alloc const& al = Alloc()){
  std::vector<T, Alloc> v(al);
  // ...
  return v;
}

Ideone での実例。

C++03 (またはその機能をサポートしていないコンパイラ) では、少し面倒ですが、テンプレート パラメーターに基づいてオーバーロードできます。

template<class T>
std::vector<T> make_vector(){
  std::vector<T> v;
  // ...
  return v;
}

template<class T, class Alloc>
std::vector<T, Alloc> make_vector(Alloc const& al = Alloc()){
  std::vector<T, Alloc> v(al);
  // ...
  return v;
}

Ideone での実例。

于 2012-02-23T10:08:27.237 に答える
0

問題は、アロケータの型がベクトルの型の一部であるため、基本的に戻り値の型が引数に依存する関数を要求していることです。を返すことでこれを行うことができboost::variantますが、これが良い考えかどうかはわかりません。クライアント コードは、ベクターを使用するために型を知る必要があります。

于 2012-02-23T10:08:19.820 に答える