Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add member to existing struct without breaking legacy code

There is the following definition in some legacy code that I am working with.

struct VlanData
{
    uint16_t mEtherType;
    uint16_t mVlanId;
};

I want to add a new member to this struct:

struct VlanData
{
    uint16_t mEtherType;
    uint16_t mVlanId;
    uint8_t mVlanPriority; // New member
};

However, use of VlanData has been fairly inconsistent through the legacy code.

Not initialized on construction:

VlanData myVlans;
myVlans.mEtherType = 0x8100;
myVlans.mVlanId = 100;

Value initialized:

VlanData myVlans = { 0x8100, 100 };

What I want to do is come up with a safe way to ensure that `mVlanPriority' is automatically set to 0 in legacy code without updating a lot of code.

I understand I could modify the legacy code to value-initialize all members like so:

VlanData myVlans = {};

But I don't want to have to update all of this code. I believe that creating a default constructor like this would help:

VlanData()
: mEtherType(0),
  mVlanId(0),
  mVlanPriority(0)
{}

But this would also destroy the POD-ness of the struct.

So I guess I have several questions:

  1. Is there a safe way I can ensure that mVlanPriority is set to 0 in legacy code without updating the legacy code?
  2. What use of the class would break if this was no longer a POD type?
like image 607
LeopardSkinPillBoxHat Avatar asked Jul 19 '11 06:07

LeopardSkinPillBoxHat


2 Answers

struct VlanData {
    struct P
    {
        uint8_t operator=(uint8_t v) { mVlanPriority = v; }
        uint8_t mVlanPriority; P() { mVlanPriority = 0; };
    };
    uint16_t mEtherType;
    uint16_t mVlanId;
    P mVlanPriority;
 };

Define other kinds of operators and add type conversion functions as you need.

eg:

int main(int argc, char** argv)
{
    VlanData myVlans0 = { };
    VlanData myVlans = { 0x8100, 100 };
    myVlans.mVlanPriority = 10;
}
like image 58
Murali VP Avatar answered Nov 02 '22 18:11

Murali VP


Is there a safe way I can ensure that mVlanPriority is set to 0 in legacy code without updating the legacy code?

No there is no standard way in current standard. You must have to have constructor.

What use of the class would break if this was no longer a POD type?

As @junjanes has mentioned in the comments, your code will be broken where you try to initialize the members with brackets.

Edit: To address your problem, I would suggest

struct VlanData
{
  uint16_t mEtherType;
  uint16_t mVlanId;
  uint8_t mVlanPriority; // New member

  VlanData(uint16_t ether, uint16_t id, uint8_t priority = 0) :
           mEtherType(ether), mVlanId(id), mVlanPriority(priority)
  {}
};

So now, your new variable will be initialized to 0 and you have to do a very less typing for fixing compilation error.

Change,

VlanData myVlans = { 0x8100, 100 };

To,

VlanData myVlans( 0x8100, 100 );
like image 1
iammilind Avatar answered Nov 02 '22 17:11

iammilind