Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read-only member variable of class

Tags:

c++

c++11

Inpired by this answer I'm using the following solution for read-only member variables:

template <class T, class OWNER>
class readonly
{
    friend OWNER;

public:
    explicit readonly(const T &t) : m_t(t)
    {
    }

    ~readonly()
    {
    }

    operator const T&() const
    {
        return m_t;
    }

private:
    T& operator =(const T &t)
    {
        m_t = t; 
        return m_t;
    }

    T m_t;
};

Which works great, to optimize performance a little I use it like this:

class A
{
public:
    A()
    {
    }

    ~A()
    {
    }

#ifdef _DEBUG     // DON'T USE THIS SWITCH, SEE ANSWERS BELOW!
    readonly<int, A> m_x, m_y;
#else
    int m_x, m_y;
#endif
};

However I would love to eliminate the precompiler switch which checks if we're doing a debug or release build... Does anyone see a solution using a macro or clever template trick?

EDIT: I've checked the performance in a loop, it generates about 15~20% overhead using VS2010. It does not result in the same code, automatic inlining enabled.

EDIT #2: I've created a unit test, eliminating all other stuff. I have no performance loss anymore, so great, there was no problem after all. Thanks for the help! And I've fixed the constructor, good call.

like image 714
demorge Avatar asked Jan 16 '23 14:01

demorge


1 Answers

Your optimisation is useless and will result in the exact same code. All of readonly is trivial and will be inlined, eliminating any overhead it might have over using raw T. So, the solution is to not fix a problem that doesn't exist, and just use readonly<int, A> regardless of whether this is debug build or not.

As @MooingDuck noted, you should change your constructor to use init list (and probably make it explicit, too).

like image 136
Cat Plus Plus Avatar answered Jan 28 '23 08:01

Cat Plus Plus