I have a deque which is supposed to hold either struct a or struct b. The problem is one of the structures contains a pointer which I have to delete.
#pragma once
#include <iostream>
#include <deque>
#include <typeinfo>
struct packetUpdate {
int recv;
int packetID;
};
struct packet {
int recv;
int packetSize;
char* m_packet;
};
template <class T>
class PacketQueue
{
private:
int m_lastElement;
int m_maxElementReached;
int m_maxElements;
std::deque<T> m_PacketList;
public:
PacketQueue() { m_lastElement = -1; m_maxElements = 0; m_maxElementReached = 0; }
~PacketQueue()
{
if(typeid(T).name() == typeid(packet).name()) {
for(int i = 0; i < m_lastElement+1; i++) {
delete[] m_PacketList[i].m_packet;
}
}
m_PacketList.~deque();
}
};
This doesn’t work. The compiler tells me that packetUpdate doesn’t have a member m_packet. I understand why it is not working but the question is, is there a way to make this work without writing two different classes which look almost the same.
This is of course only a small selection of the class but it should illustrate my problem.
I guess I’m not the first one who had such a problem but since I’m not used to work with templates that much I didn’t know what I should look for.
The absolut easiest way to do it is just to add destructor to packet. If that is not a possibility you can add a policy template to solve your problem:
Then when you add a type which needs cleaning you hand in a different Cleaner:
Also there is no need for the specific call to m_PacketList.~deque() in fact it will just break your program because the compiler ensures it will be called anyway (so you are just calling it twice).
Also the reason why you get compiler errors because m_packet doesn’t exist is that the if-block is compiled regardless of whether T == packet or T == packetUpdate and for packetUpdate there is no m_packet.