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.
VlanData myVlans;
myVlans.mEtherType = 0x8100;
myVlans.mVlanId = 100;
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:
mVlanPriority
is set to 0 in legacy code without updating the legacy code? POD
type?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;
}
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With