forGreatJustice

…take off every ZIG!

RSS Feeds

  • Home
  • About

The Gang of Three

Jul 23rd

Posted by Arron in Programming

No comments

I’ve recently been working on a project that involved a whole load of code that wasn’t written by myself or anyone at the company I work for. Suffice to say, there’s a fair few problems. Anyway, I’ve been stuck on a bug that’s been stringing me a long for the past week now. At first I thought it was a multithreading problem as we’ve had to convert all the original POSIX threading code to Windows Threads. Turns out however that it was simply a case of bad memory management, which brings me to the subject of this post: The Gang Of Three.

The actual cause of the rogue bug was due to the lack of an implemented copy constructor in one of the authors classes. The code looked a bit like this:

AClass.cpp:
class AClass
  {
  private:
    int*    m_pData;
  public:
    AClass()
    {
    m_pData = new int[10];
    }
    ~AClass()
    {
    delete [] m_pData;
    }
  void AddVals(int nVal1, int nVal2, int nVal3);
  };
SomeFile.cpp:
AClass GetVals()
  {
  AClass aObj;
  aObj.AddVals(1, 5, 7);
  return aObj;
  }

...

AClass aVals = GetVals();

… which doesn’t look too harmless (apart from the return by value). It wasn’t until I took a look in AClass.cpp and noticed that memory was been allocated in the constructor. See the potential problem yet? Line 4 of SomeFile.cpp constructs a new object of AClass and the AClass constructor invokes an allocation of memory. Line 6 returns the newly constructed aObj by value and invokes the default copy constructor (not operator=) on aVals, shallow copying the data from aObj into aVals. aObj is now out of scope and the destructor gets called on aObj, freeing the memory within. However, because m_pData within aObj was just shallow copied to aVals, aVals::m_pData still points to same memory location that aObj::m_pData pointed to.. and it’s just been free’d! So now aVals::m_pData points to invalid memory and any subsequent usage of said pointer will likely result in a crash immediately if you’re lucky, or n lines later if you aren’t (like me).

So what’s the point of all this rambling? Obey the Gang of Three! What’s the Gang of Three you ask? Destructor, Copy Constructor and Assignment Operator. If you need one of these three, you need them ALL. Even if you don’t ever intend to copy a class or do something silly like the example I posted above, no doubt someone will. If you don’t want people to make a copy of your objects, just make the copy constructor and assignment operator private.

Wondering exactly how to implement the Gang of Three? Here’s AClass from above expanded to include these functions:

AClass.cpp:
class AClass
  {
  private:
    int*    m_pData;

  public:
    AClass()
    {
    m_pData = new int[10];
    }

    ~AClass()
    {
    delete [] m_pData;
    }

    AClass(const AClass& copy)                 // Copy constructor
    {
    int* pMem = new int[10];  // Allocate memory
    // Perform deep copy e.g:
    for(int nIndex = 0; nIndex < 10; nIndex++)
        pMem[nIndex] = copy.m_pData[nIndex];

    m_pData = pMem;           // Assign new memory to m_pData
    }

    AClass& operator=(const AClass& rhs)       // Assignment operator
    {
    if(this != &rhs) // Don't want to self assign!
      {
      int* pNewMem = new int[10];   // Allocate new memory
      // Deep copy memory

      delete [] m_pData;            // Delete old data
      m_pData = pNewMem;            // Assign new memory to m_pData
      }
    return *this;
    }
  void AddVals(int nVal1, int nVal2, int nVal3);
  };

So to summarise: if you need to implement a destructor 99% of the time you should always ALWAYS ALWAYS implement a copy constructor and assignment operator lest you be cast down to memory hell!

C++, Memory Management

Useful mathematical functions for the 3D Programmer

Feb 22nd

Posted by Arron in Programming

No comments

Here’s a collection of useful maths functions that I find I use a fair amount while programming 3D graphics. Some/all of these may be obvious, but I’m posting them here for reference anyway. While I was studying I would’ve quite liked a list like this. So without further ado…

Vector functions

  1. Dot product. Returns a floating point number describing the difference between two given vectors. Useful for determining clipping, lighting, physics, etc. The bread and butter of vector mathematics. If the two vectors are normalised, the inverse cosine ( acos(…) ) of the dot product will give you the angle in radians between them, which is nice.
  2. Cross product. Returns a vector which is perpendicular to two given vectors. Not as useful as dot product, but applicable in situations such as camera matrix construction, and determining axis of rotation.

Trig functions

The following functions can be found in the C++ standard maths library (#include <cmath>)

  1. cos(…) / sin(…). Never underestimate the power of trig! Useful on a daily basis, not only because they’re the basis of vector maths. Just using cosine and sine to create smooth oscillations is a massive boon to the 3D programmer. Use judiciously. Oh, all trig-based functions found in the C++ standard maths library take and return radians, not degrees! If you want to convert degrees to radians, see below.
  2. Degrees to radians. I don’t know about you, but I find it much easier to think of my rotations in degrees rather than radians. Simple things such as PI/2 is all well and good, but debugging radians is a bit of a nightmare. Here’s a C++ macro to convert from degrees to radians (appropriately modify if you use 64-bit floating point variables i.e double):
    • #define DEG2RAD(x) ((x) * 3.141592f / 180.0f)
  3. atan2(y, x). Returns the inverse tangent of the two values, in radians. This is basically the angle in radians between the provided arguments and positive x. Pretty useful for 2D games and such, although not so useful if you’re already using vectors.

Yeah so they weren’t that many after all, but I’ll add to this list as more come to mind.

3D, C++, Maths

My nth attempt at running a blog.

Dec 3rd

Posted by Arron in Website

No comments

Well, I had to take down my portfolio website as I was still being contacted by job agencies, despite being employed for the past 4 months. So anyways, I decided I’d give blogging another shot. I’ve never been very successful at running a blog before, so we’ll just have to see. Plus I pirated a copy of 101 Blog Ideas. Gahaha.

ideas
  • Categories

    • Programming
    • Website
  • Tags

    3D C++ ideas Maths Memory Management
  • About Me

    I'm a Computer Games Programmer working in the North of England specialising in C++ and OpenGL. I also work on iPhone programming as a hobby in my spare time.
Mystique theme by digitalnature | Powered by WordPress