Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm creating a class which uses a custom buffer. I want to offer the possibility to pass an external memory address (for higher interoperability between languages) or (for convenience) to specify a custom allocator type. The following code outlines what I mean:

template<typename int_type, class alloc = void>
class uses_custom_buffers
    : uses_custom_buffers<int_type, void>
{
public:
    uses_custom_buffers<int_type, alloc>* set_buffer(std::size_t count, std::size_t size)
    {
        typename alloc::rebind<int_type*>::other pointer_alloc;
        int_type** buffer = pointer_alloc.allocate(count);
        for (std::size_t i = 0; i < count; ++i)
            buffer[i] = this->m_alloc.allocate(size);
        this->uses_custom_buffers<int_type, void>::set_buffer(count, buffer, size);
        return this;
    }

private:
    using uses_custom_buffers<int_type, void>::set_buffer;

    alloc m_alloc;
};

template<typename int_type>
class uses_custom_buffers<int_type, void>
{
public:
    uses_custom_buffers<int_type, void>* set_buffer(std::size_t count, int_type** buffers, std::size_t size)
    {
        this->m_buf   = buffers;
        this->m_count = count;
        this->m_size  = size;
        return this;
    }

private:
    int_type**  m_buf;
    std::size_t m_count,
                m_size;
};

Please note: This example doesn't care about deallocating any resource or exception safeness (to simplify matters). Do you see any kind of problems with that design?

share|improve this question

migrated from stackoverflow.com Jun 25 '11 at 11:10

This question came from our site for professional and enthusiast programmers.

    
Is this the entire code? Where is the base declaration of uses_custom_buffers? And is it an option to follow the STL allocator design? –  Kerrek SB Jun 25 '11 at 10:49
    
@Kerrek: The base is a specialization of itself. –  Xeo Jun 25 '11 at 11:06
    
@Xeo: Does that work? I think I misread one of my compiler errors! D'oh. Thanks! –  Kerrek SB Jun 25 '11 at 11:24
    
@Kerrek SB - I'm following the STL allocator design. The template argument "alloc" could be any STL conform allocator type. That's exactly the same technique the STL containers are using. –  0xbadf00d Jun 25 '11 at 12:07
    
I see. Hm. My compiler suggests you say typename alloc::template rebind<int_type*>::other pointer_alloc; –  Kerrek SB Jun 25 '11 at 12:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.