dc2000 wrote:
Hi everyone:
Can someone explain why am I getting "Access violation" in this code:
//Declaration
typedef struct _MY_VARS{
int v1;
int v2;
}MY_VARS, *LPMY_VARS;
typedef struct _MY_TYPE{
int nVar;
CArray<MY_VARS, MY_VARS>* pArr;
_MY_TYPE()
{
pArr = new CArray<MY_VARS, MY_VARS>;
}
~_MY_TYPE()
{
if(pArr)
delete pArr; //"Access violation" raised here from arr.Add() call
}
}MY_TYPE, *LPMY_TYPE;
//Use
CArray<MY_TYPE, MY_TYPE> arr;
MY_TYPE v;
arr.Add(v); //When called, raises "Access violation"
dc:
In order to go in CArray, MY_TYPE must have a copy constructor and
assignment operator that "do the right thing". The default ones just
copy the pointer pArr, so the same pointer can be deleted by two
different objects.
Just guessing, but is the reason you made the array inside MY_TYPE a
pointer because you could not get it to compile if it was a non-pointer
member? If so, this happened because CArray itself does not have copy
constructor and assignment operator (they are disabled in the base class
CObject).
My advice: get rid of CArray and use std::vector instead. Then you can do
struct MY_VARS
{
int v1;
int v2;
};
struct MY_TYPE
{
int nVar;
std::vector<MY_VARS> arr;
}
//Use
std::vector<MY_TYPE> arr;
MY_TYPE v;
arr.Add(v);
David Wilkinson