Lost Website

You Are Here

Naivety with C++

with one comment

Warning, major n00bness ahead.

I’m not a big user of C++, but recently some work I have had to do with .NET has made me use C++/CLI, the .NET version of C++.

The API I work have a well defined and consistent Alloc/Use/Free cycle. This has gave me an incentive to learn to use RAII (via DrMax) to elegantly wrap the required cleanup operation in my code.

The following class around Windows GlobalAlloc is an example of such a wrapper.

    // RAII friendly wrapper over Win32 GlobalAlloc.
    class Memory
    {
    private:
        bool m_isAlloc;

    public:
        HGLOBAL Ptr;
        SIZE_T Size;

        void Alloc(UINT flags, size_t dwBytes)
        {
            if (IsAlloc()) Free();
            Size = dwBytes;
            Ptr = GlobalAlloc(flags, dwBytes);
            if (Ptr == 0)
                throw gcnew OutOfMemoryException();
            m_isAlloc = 1;
        }

        void Free()
        {
            if (Ptr) GlobalFree(Ptr);
            m_isAlloc = 0;
            Size = 0;
            Ptr = 0;
        }

        bool IsAlloc()
        {
            return m_isAlloc;
        }

        Memory(UINT flags, size_t dwBytes)
        {
            Alloc(flags, dwBytes);
        }

        Memory()
        {
            Ptr = 0;
        }

        ~Memory()
        {
            if (Ptr) GlobalFree(Ptr);
        }
    };

Expert eyes will obviously see that this code lacks 2 important things:

  • there is no copy constructor
  • there is no assignment operator

I’m not very experienced in C++ so I don’t the reflexes that make C++ programmers write those things when the define a class, and I don’t yet know when the implicit copy constructor and assignment operator are called. I’ve found that the easiest way to discover that is to to prevent them from being usable by the clients of the class. In the case of my small class above, I needed to make 2 functions private.

class Memory {
...
private:
    Memory& operator=(const Memory& mem);
    Memory(const Memory& mem);
...

This makes the compiler freak out when compiling my program…

...Memory::operator =' : cannot access private member declared in class 'Memory'...

The compiler has helpfully pointed to me out which place in my code those functions needs to be called.

Oops, so I really need that assignment operator after all.

Written by fdgonthier

October 27th, 2009 at 8:00 pm

Posted in C++,Programming

Tagged with , , , ,

One Response to 'Naivety with C++'

Subscribe to comments with RSS or TrackBack to 'Naivety with C++'.

  1. [...] This is something tedious and error-prone but unavoidable when you are using COM objects in C. Luckily, C++.NET isn’t C and it means we can use RAII, just like the code I presented in Naivety in C++. [...]

Leave a Reply