1
\$\begingroup\$

I am trying to write a simple Buffer container class that will behave like std::vector. It should construct only elements that are truly within the buffer, so the rest of the buffer ([size, capacity)) is left uninitialized.

This is my current copy assignment operator:

template <typename Type, typename Allocator>
    Buffer<Type,Allocator>&
        Buffer<Type,Allocator>::operator=(const Buffer<Type,Allocator>& copy)
    {
        if(this != &copy) {
            SizeType old_size = getSize();
            if(getCapacity() != copy.getCapacity()) {
                for(SizeType i = 0; i < old_size; ++i) {
                    Allocator::destruct(_m_membegin+i);
                }
                Allocator::deallocate(_m_membegin);
                _m_membegin = Allocator::allocate(copy.getCapacity());
                _m_memend = _m_membegin+copy.getCapacity();
                _m_end = _m_membegin+copy.getSize();
                SizeType new_size = getSize();
                for(SizeType i = 0; i < new_size; ++i) {
                    Allocator::construct(_m_membegin+i,copy[i]);
                }
            } else {
                _m_end = _m_membegin+copy.getSize();
                SizeType new_size = getSize();
                for(SizeType i = 0; i < old_size; ++i) {
                    _m_membegin[i] = copy[i];
                }
                for(SizeType i = old_size; i < new_size; ++i) {
                    Allocator::construct(_m_membegin+i,copy[i]);
                }
            }
        }
        return *this;
    }

Allocator::allocate is just a wrapper around ::operator new, same thing with deallocate. construct is a wrapper around placement new and destruct is only explicit destructor call on a given type pointer.

How can I clean up this code a little bit? Also, do you see any potential memory leaks?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.