I'm writing a packet processor and have the following classes:
class Parser {
private:
Packet* curr_pkt;
public:
void parsePacket(unsigned char byte) {
if(byte == SyncPacket::headerVal) {
SyncPacket pkt;
curr_pkt = &pkt;
}
if(byte == SyncPacket::headerVal) {
TypeAPacket pkt;
curr_pkt = &pkt;
}
}
};
class Packet {
public:
void parseByte(unsigned char byte) {}
};
class SyncPacket : public Packet {
public:
static const unsigned char headerVal = 0x0A;
void parseByte(unsigned char byte) {
<do sync>
}
};
class TypeAPacket : public Packet {
public:
static const unsigned char headerVal = 0x0B;
void parseByte(unsigned char byte) {
<do type A decode>
}
};
int main() {
std::vector<unsigned char> chars;
<stream in characters>
Parser pktParser;
for(unsigned char byte: bytes) {
pktParser.parseByte(byte);
}
}
This seems to work fine and is in fact what I think polymorphism is for. But my question is: should I be worried about the raw pointer use here? Would there be a more recommended way to do this via smart pointers?
For example, in this line:
if(byte == SyncPacket::headerVal) {
SyncPacket pkt;
curr_pkt = &pkt;
}
Technically, pkt is out of scope after the if statement, so normally it's lifetime would be over. But because curr_pkt is pointing to it, it lives on. This is a potential issue, isn't it?