Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers or references for dynamically allocated members that always exist?

I have a class CContainer that has some members CMemberX, CMemberY, which are independent of each other and other CClientA, CClientB classes that use CContainer.

#include "MemberX.h"
#include "MemberY.h"

class CContainer
{
public:
    CMemberX & GetX() const { return m_x; }
    CMemberY & GetY() const { return m_y; }

private:
    CMemberX m_x;
    CMemberY m_y;
};

I want to avoid having to recompile all CClient classes when modifying one of the CMember classes using forward declarations and dynamic allocation of m_x and m_y.

Initially, I made the members pointers:

// Container.h
class CMemberX;
class CMemberY;

class CContainer
{
public:
    CContainer();
    ~CContainer();

    CMemberX & GetX() const { ASSERT(m_pX != NULL); return *m_pX; }
    CMemberY & GetY() const { ASSERT(m_pY != NULL); return *m_pY; }

private:
    CMemberX* m_pX;
    CMemberY* m_pY;
};

// Container.cpp
#include "Container.h"
#include "MemberX.h"
#include "MemberY.h"

// Allocate members on heap
CContainer::CContainer() : m_pX(new CMemberX()), m_pY(new CMemberY()) {}
CContainer::~CContainer() { delete m_pX; delete m_pY; }

Then I thought, that I could as well use references instead of pointers, so it looks more like the original code:

// Container.h
class CMemberX;
class CMemberY;

class CContainer
{
public:
    CContainer();
    ~CContainer();

    CMemberX & GetX() const { return m_x; }
    CMemberY & GetY() const { return m_y; }

private:
    CMemberX & m_x;
    CMemberY & m_y;
};

// Container.cpp
#include "Container.h"
#include "MemberX.h"
#include "MemberY.h"

// Allocate members on heap
CContainer::CContainer() : m_x(*new CMemberX()), m_y(*new CMemberY()) {}
CContainer::~CContainer() { delete &m_x; delete &m_y; }

What I don't like about the pointer members is that it looks like the pointers could be NULL or the objects be replaced at runtime, which is not the case.

What I don't like about the references is that the code in the CTor and DTor looks a bit hacky.

Which approach is preferable? Is there a better solution?

Note regarding copying/assigning: Instances of the CContainer class will not under any circumstances be copied or assigned to each other.

like image 734
foraidt Avatar asked May 15 '26 14:05

foraidt


1 Answers

I think that's what the const variables are for:

CMember * const m_x;

Cannot change m_x after initialization...