C++ c++;:删除对象并将对象转换回父类成员的位置
我有一个简单的消息类和一个简单的SerialPort类。我还有一个特定的消息子类和一个特定的串行端口子类(CustomMessage和CustomSerialPort): 下面是自定义类。注意,我重载了WriteToSerial()以获取CustomMessage,而不仅仅是MessageC++ c++;:删除对象并将对象转换回父类成员的位置,c++,oop,serial-port,C++,Oop,Serial Port,我有一个简单的消息类和一个简单的SerialPort类。我还有一个特定的消息子类和一个特定的串行端口子类(CustomMessage和CustomSerialPort): 下面是自定义类。注意,我重载了WriteToSerial()以获取CustomMessage,而不仅仅是Message class CustomSerialPort : public SerialPort { public: bool WriteToSerial(int32& errcode, CustomMe
class CustomSerialPort : public SerialPort
{
public:
bool WriteToSerial(int32& errcode, CustomMessage& msg,
uint32* const nBytesWritten);
...
}
class CustomMessage : public Message
{
// lots of stuff for messages to specific device
}
同样重要的是,CustomSerial::WriteToSerial和CustomMessage::toMessage()的实现
您可以看到,我调用SerialPort类的WriteToSerial并向其发送一条已转换为消息的CustomMessage
class CustomSerialPort : public SerialPort
{
public:
bool WriteToSerial(int32& errcode, CustomMessage& msg,
uint32* const nBytesWritten);
...
}
class CustomMessage : public Message
{
// lots of stuff for messages to specific device
}
我的问题是:我应该在哪里删除我创建的传递给SerialPort::WriteToSerial的消息?
或者,我应该做更多类似的事情:
bool CustomSerialPort::WriteToSerial(int32& errcode, CustomMessage& msg,
uint32* const nBytesWritten)
{
// don't use new
Message m(msg);
SerialPort::WriteToSerial(errcode, m, nBytesWritten);
// deleted when goes out of scope
}
然后,对于选项2,如果我的理解是正确的,我只需要创建一个消息构造函数,它接受CustomMessage的一个参数。。。等待这似乎很奇怪。。在父类构造函数中获取子类对象参数。我需要重新考虑吗?您不需要在toMessage()中添加新消息,也不需要删除它 改变
Message& CustomMessage::toMessage()
{
Message* msg = new Message(m_contents, m_length);
return *msg;
}
bool CustomSerialPort::WriteToSerial(int32& errcode, CustomMessage& msg,
uint32* const nBytesWritten);
到
在WriteToSerial中调用toMessage()
时,它将被绑定,直到WriteToSerial()函数完成
此外,您还需要向所有函数添加const限定符,将消息作为输入
class SerialPort
{
public:
bool OpenSerial(int32& errcode);
bool ReadFromSerial(int32& errcode, const Message& msg);
bool WriteToSerial(int32& errcode, const Message& msg,
uint32* const nBytesWritten);
...
}
尽可能不要使用new
。您唯一应该使用new的时间是:
1.您无法事先知道需要多少对象,而且“少”和“多”之间的可能范围相差太大,因此使用固定大小的数组或类似数组是不合理的。
2.当对象必须比当前函数持续更长的时间,并且从较低的函数传入对象是不合理的。
3.在创建对象之前无法知道对象的类型(在多态性方面尤其相关)
不使用new
会有所帮助,因为您不必记得以后删除它
如果您确实使用了new
,那么最好将它放在资源存放对象(智能指针或类似对象)中,这样您就不必记住删除它 选项2是切片问题的一个例子,所以我不建议使用它。@Csq我想我将使用下面的billz答案,但如果我不关心切片过程中丢失的信息(例如,我将需要的所有信息存储在缓冲区中),该怎么办,包括CustomMessage中存储在成员变量中的所有特定于消息的内容,有点像序列化函数。如果我计划在之后立即发送它,那么切片会很糟糕吗?不,它会正常工作,但这种奇怪的解决方案会导致代码的可维护性差,所以通常您应该避免它们。我真的想要:bool ReadFromSerial(int32&errcode,const Message&msg);当我需要向从序列号读取的消息添加信息时?添加const不会阻止这一点吗?
Message CustomMessage::toMessage()
{
return Message(m_contents, m_length);
}
bool CustomSerialPort::WriteToSerial(int32& errcode, const CustomMessage& msg,
^^^ const
uint32* const nBytesWritten)
class SerialPort
{
public:
bool OpenSerial(int32& errcode);
bool ReadFromSerial(int32& errcode, const Message& msg);
bool WriteToSerial(int32& errcode, const Message& msg,
uint32* const nBytesWritten);
...
}