I Have a similar issue like the one listed here pointer-to-a-pointer-to-a-struct-giving-headache
my issue is different because i don't want multi instances from LISTOFONES i want Multi instances of ONE's Pointers 开发者_StackOverflow中文版likeclass ONE {
int id;
char *name;
};
class LISTOFONES {
ONE **pointers;
char *name;
LISTOFONES ();
~LISTOFONES ();
};
What to do to have a correct and memory safe initialization of the pointers variable with
1- pure c++ .. not stl containers 2- 100% dynamic not [] array limitation 3- Completely Memory Safe ( All Pointers safely point to a valid class too )EDIT:
This is Not Home Work and For what i want i only want to know what is the method to correctly init the pointers in the 'pointers' variableEDIT
I Am trying to Achieve a Pointer List (array) Pointed by the Pointer pointers Each Pointer points to the ONE structIf it were me, I would allocate an array of ONE*
s thus:
pointers = new ONE*[reserve];
I would arrange that the first several members of the pointers
array pointed to valid ONE objects. The last remaining members would all be zero (not essential, since they will never be derferenced.)
When I needed to grow the array, I would call new with a bigger size:
newPointers = new ONE*[newReserve];
and I would copy all of the pointers from previous array to the new array.
void
LISTOFONES::push_back(const ONE& one) {
if(_size>=_reserve) {
std::size_t newReserve = _reserve?(_reserve*2):1;
ONE** newPointers = new ONE*[newReserve];
std::copy(this->pointers, this->pointers+_size, newPointers);
std::fill(newPointers+_size, newPointers+newReserve, (ONE*)0);
std::swap(this->pointers, newPointers);
_reserve = newReserve;
delete[] newPointers;
}
this->pointers[_size] = new ONE(one);
++_size;
}
精彩评论