I have an abstract class, IPacket.
/*
* Represents an abstract network packet.
*/
class IPacket
{
public:
virtual void read(...) = 0;
virtual void write(...) = 0;
virtual int getID() const = 0;
};
And I'd like to (and have been) returning a pointer to like so:
class PacketMedium
{
/*!
* Returns a pointer to the next pending packet or NULL if there are no packets pending.
* \note The object must deleted when you are finished with it.
*/
IPacket* receivePacket();
};
Now obviously, this is bad practice; requiring the caller to delete a pointer that wasn't even allocated by itself. The convention I believe, is to use smart pointers, i.e.
class PacketMedium
{
public:
std::unique_ptr<IPacket*> receivePacket();
};
But as this is library code, smart pointers are a nono, notwithstanding the fact I'd prefer to avoid them regardless.
What would my best option be?
Thanks for any help :)
EDIT: this has been asked before and very good answers were given, although they all suggest smart pointers, or just not allocating on the heap. Given that IPacket
is abstract, stack allocation wouldn't work.