Reputation:
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.
Upvotes: 0
Views: 62
Reputation: 258678
This should work, but m_PacketList.~deque();
in the destructor is a bad idea, the destructor of the queue will be called anyway, and thus you're calling it twice.
Upvotes: 1
Reputation: 2016
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:
struct null_cleaner
{
template <typename T>
void perform_clean(T& v)
{ /* do nothing */ }
};
template <typename PacketQueue, typename Cleaner = null_cleaner>
class PacketQueue
{
~PacketQueue ()
{
for (int i = 0; i < m_PacketList.size(); ++i) {
Cleaner::perform_clean(m_PacketList[i]);
}
}
};
Then when you add a type which needs cleaning you hand in a different Cleaner:
// no cleaning
PacketQueue<packetUpdate> q1;
// requires cleaning
struct packet_cleaner
{
void perform_clean(packet& p)
{
delete[] m_packet;
}
};
// performs cleaning
PacketQueue<packet, packet_cleaner> q2;
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.
Upvotes: 0
Reputation: 1099
You could specify you class destructor for the type packet, like this:
template<>
PacketQueue<packet>::~PacketQueue()
{
//your code
}
Upvotes: 0