I have written a Queue class for our use that stores pointers to what I call RequestObjects. RequestObjects are a base class from which other types inherit and this allows the queue (or deque in this case) to hold values of different types. When popping values off the deque, the values are then typecasted back to their useful derived type. So far the class has worked well except with strings. When string values are typecasted back to be read off the deque the program segfaults. Here's a quick example of the code and the result of the unit test at the bottom:
I've debugged this as far as my understanding can take me but cannot figure out why the string becomes corrupted but the other values don't. Any help or ideas?
Thanks!
-Marco
Code:
// Queue.h
class RequestObject
{
public:
// Constructor
RequestObject(){ mType = -1; }
virtual ~RequestObject(){}
int GetType() const { return mType; }
void SetType(int i) { mType = i; }
private:
int mType;
};
template <class T>
class SingleValueReq : public RequestObject
{
public:
SingleValueReq(){ mValue = NULL; }
SingleValueReq(T b){ mValue = new T(b); }
virtual ~SingleValueReq(){ delete mValue; }
void SetValue(T value){ delete mValue; mValue = new T(value); }
T GetValue(){ return(*mValue); }
private:
T *mValue;
};
class QueueObject
{
public:
QueueObject(){}
~QueueObject(){}
// Public Methods
bool Empty();
RequestObject *Pop();
void Clear();
// Add mechanism
template <typename T>
void Add(int type, T value)
{
SingleValueReq<T> *O = new SingleValueReq<T>(value);
O->SetType(type);
Q.push_back(O);
// debug code
O = (SingleValueReq<T> *)Q.back();
std::cout << "Add " << O->GetValue() << std::endl;
}
private:
std::deque<RequestObject *> Q;
};
// From file Queue.cpp
RequestObject *QueueObject::Pop()
{
RequestObject *O = Q.front();
Q.pop_front();
return(O);
}
bool QueueObject::Empty()
{
return(Q.empty());
}
// From test program QueueTest.cpp
int main(int argc, char *argv[])
{
QueueObject mQ;
mQ.Add(10, -1.0);
mQ.Add(11, true);
mQ.Add(12, -1);
mQ.Add(13, false);
mQ.Add(14, "StringTest!!!");
while(!mQ.Empty())
{
RequestObject *O = mQ.Pop();
switch(O->GetType())
{
case(10):
{
SingleValueReq<double> *ip = (SingleValueReq<double> *)(O);
cout << "Value = " << ip->GetValue();
}
break;
case(11):
{
SingleValueReq<bool> *ip = static_cast<SingleValueReq<bool> *> (O);
cout << "Value = " << ip->GetValue();
}
break;
case(12):
{
SingleValueReq<int> *ip = static_cast<SingleValueReq<int> *> (O);
cout << "Value = " << ip->GetValue();
}
break;
case(13):
{
SingleValueReq<bool> *ip = static_cast<SingleValueReq<bool> *> (O);
cout << "Value = " << ip->GetValue();
}
break;
case(14):
{
SingleValueReq<string> *ip = (SingleValueReq<string> *) (O);
cout << "Value = " << ip->GetValue();
}
break;
default:
break;
}
cout << endl;
}
return(0);
}
// Sample output from QueueTest.cpp
]./QueueTest
Add -1
Add 1
Add -1
Add 0
Add StringTest!!!
Value = -1
Value = 1
Value = -1
Value = 0
Segmentation fault
Thanks!
-Marco
Comment