Can anyone check my memory class and suggest changes or things I may need? I'm writing it so that I don't have to worry about deleting anything everytime I allocate.

#include <iostream>

template<typename T>
class Memory
{
    private:
        size_t size;
        T* data;

    public:
        explicit Memory(size_t Size) : size(Size), data(new T[Size]){}
        ~Memory()
        {
            if (data)
                delete[] data;
        }

        Memory(Memory& Block) : size(Block.size), data(new T[Block.size])
        {
            //if (data)
                //delete[] data;
            std::copy(Block.data, Block.data + size, data);
        }

        /*
        Memory(Memory& Block) : size(Block.size)
        {
            if (data)
                delete[] data;
            data = new T[Block.size];
            std::copy(Block.data, Block.data + size, data);
        }
        */

        Memory& operator = (Memory& Block)
        {
            if (this != &Block)
            {
                delete[] data;
                size = Block.size;
                data = new T[size];
                std::copy(Block.data, Block.data + size, data);
            }
            return *this;
        }

        size_t Size() const
        {
            return size;
        }
};

I'm writing it so that I don't have to worry about deleting anything everytime I allocate.

While writing your own smart pointer is a good exercise, it shouldn't be preferred over the ones already available in C++11 and Boost. I'd recommend studying the interface for those and how they work for ideas on ways to improve your own Memory class.

Well, I happen to have written a tutorial on how to write a class like that. Read it here.

Your class is no different than the standard std::vector class (except that the standard class has way more features). So, I recommend you use that instead.

I wrote my first smart-pointer class in the early 90's which implemented a reference-counting garbage collection pattern. It is used for the most widely utilized manufacturiing execution systems software in the semiconductor, flat-panel display, and disc drive industries. In 10M lines of code, there are no deletes and no memory leaks. The hardest part was dealing with recursive (circular) references. So, what decptikon said - look at the implementation of the standard smart pointer classes/templates that are in the current C++ standard, and other frameworks such as Qt and Boost.

commented: 10M LOCs no deletes? That's how it should be! But, isn't there one delete in the smart-pointer definition? +13
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.