I am changing my current implementation of a message class from:
class Message
{
public:
Message(uint8* buffer, uint8 length) : m_contents(buffer), m_length(length) { }
uint8 getLength() const {return m_length; }
const uint8* getData() const { return m_contents; }
protected:
uint8* m_contents;
uint8 m_length;
};
To take only length in the constructor, and dynamically allocate in the constructor, and delete in the destructor.
I think it should look like:
Message(uint8 length) : m_length(length)
{
m_contents = new uint8[length];
}
~Message()
{
delete [] m_contents;
m_contents = NULL;
}
Additional info: The message object will be passed to a serial port object which will send it off. It will also be subclassed into multiple CustomMessage classes.
My question is: in this simple example, are there any reasons to use some type of smart pointer? An example would be helpful. Thanks!
Actually it depends. Consider this code:
Do you want
m2to be a deep-copy ofm1? Do you want the underlying buffer ofm1andm2to share memory? Or you don’t want the copy to begin with (deep or otherwise)? That is, the second statement should result in compilation error?std::shared_ptr.If you want them to be completely different copy in memory (deep-copy), then no, you should not use
shared_ptr; you can usestd::unique_ptrthough, but you have to implement copy-semantic also. But then if you go with this case, then it is better to usestd::vector<uint8>instead of implementing your own class:If you want to prevent copy and thus the second statement should result in compilation error, then you’ve to disable copy-semantic by
=deleteingthem as:Note that in this case you’ve to implement the move-semantic yourself. Move usually makes sense, so I wouldn’t comment on that.
Hope that helps.