Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow member to be const while still supporting operator= on the class

I have several members in my class which are const and can therefore only be initialised via the initialiser list like so:

class MyItemT
{
public:
    MyItemT(const MyPacketT& aMyPacket, const MyInfoT& aMyInfo)
        : mMyPacket(aMyPacket),
          mMyInfo(aMyInfo)
    {
    }

private:
    const MyPacketT mMyPacket;
    const MyInfoT mMyInfo;
};

My class can be used in some of our internally defined container classes (e.g. vectors), and these containers require that operator= is defined in the class.

Of course, my operator= needs to do something like this:

MyItemT&
MyItemT::operator=(const MyItemT& other)
{
    mMyPacket = other.mPacket;
    mMyInfo = other.mMyInfo;
    return *this;
}

which of course doesn't work because mMyPacket and mMyInfo are const members.

Other than making these members non-const (which I don't want to do), any ideas about how I could fix this?

like image 917
LeopardSkinPillBoxHat Avatar asked Apr 12 '10 06:04

LeopardSkinPillBoxHat


2 Answers

You're kind of violating the definition of const if you have an assignment operator that can change them after construction has finished. If you really need to, I think Potatoswatter's placement new method is probably best, but if you have an assignment operator your variables aren't really const, since someone could just make a new instance and use it to change their values

like image 124
Michael Mrozek Avatar answered Oct 12 '22 17:10

Michael Mrozek


Rather than storing objects in your containers directly, you might be able to store pointers (or smart pointers). That way, you don't have to mutate any of the members of your class -- you get back exactly the same object as you passed in, const and all.

Of course, doing this will probably change the memory management of your application somewhat, which may well be a good enough reason not to want to.

like image 29
Andrew Aylett Avatar answered Oct 12 '22 19:10

Andrew Aylett