1

我有一个简单的 Message 类和一个简单的 SerialPort 类。我还有一个特定的消息子类和一个特定的串口子类(CustomMessage & CustomSerialPort):

class Message
{
public: 
    uint8 getLength() const ( return m_length; }
    const uint8* getData() const { return m_contents; }
...
}

class SerialPort
{
public:
    bool OpenSerial(int32& errcode);  
    bool ReadFromSerial(int32& errcode, Message& msg);  
    bool WriteToSerial(int32& errcode, Message& msg, 
        uint32* const nBytesWritten);
...
}

这是自定义类。请注意,我重载了 WriteToSerial() 以获取 CustomMessage 而不仅仅是 Message。

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() 的实现

bool CustomSerialPort::WriteToSerial(int32& errcode, CustomMessage& msg, 
    uint32* const nBytesWritten)
{
    SerialPort::WriteToSerial(errcode, msg.toMessage(), nBytesWritten);
}

Message& CustomMessage::toMessage() 
{
    Message* msg = new Message(m_contents, m_length);
    return *msg;
}

可以看到我调用了SerialPort类的WriteToSerial,给它发送了一个已经转换为Message的CustomMessage。

我的问题是:我应该在哪里删除我创建的传递给 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 参数的 Message 构造函数......等等......这看起来很奇怪......在父类构造函数中采用子类对象参数。我需要重新考虑这个吗?

4

2 回答 2

2

您不需要new Message进入 toMessage() 也不需要删除它。

改变

Message& CustomMessage::toMessage() 
{
    Message* msg = new Message(m_contents, m_length);
    return *msg;
}

bool CustomSerialPort::WriteToSerial(int32& errcode, CustomMessage& msg, 
    uint32* const nBytesWritten);

Message CustomMessage::toMessage() 
{
    return Message(m_contents, m_length);
}

bool CustomSerialPort::WriteToSerial(int32& errcode, const CustomMessage& msg, 
                                                     ^^^ const
    uint32* const nBytesWritten)

toMessage()WriteToSerial 中调用时,它将被绑定,直到 WriteToSerial() 函数完成。

您还需要为所有函数添加const限定符Message作为输入

class SerialPort
{
public:
    bool OpenSerial(int32& errcode);  
    bool ReadFromSerial(int32& errcode, const Message& msg);  
    bool WriteToSerial(int32& errcode, const Message& msg, 
        uint32* const nBytesWritten);
...
}
于 2013-01-19T22:53:14.810 回答
1

只要有可能,不要使用new. 唯一应该使用 new 的时间是: 1. 您无法事先知道需要多少个对象,并且“少数”和“很多”之间的可能范围差异很大,因此使用固定大小的数组或类似数组是不合理的. 2. 当对象必须比你当前的函数持续更长时间,并且从较低的函数传递对象是不合理的。3. 对象的类型在对象被创建之前是无法知道的(尤其是多态性)。

不使用new帮助是因为您以后不必记住delete它。

如果您确实使用new,那么最好将它放在一个资源持有对象中 - 智能指针或类似的东西 - 这样,您就不必记住删除它。

于 2013-01-19T22:58:32.203 回答