Re: pointer to an array of pointers - allocate
On Jan 20, 6:27 pm, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
Christopher wrote:
I need to have an array of pointers to something. I do not know how
many I will have until runtime. How do you allocate?
You don't. Use a vector<int*>.
[rearranged:]
It needs to be in the form: type **, because the API I am using asks
for it in that way.
No it doesn't need to be int**. With
vector<int*> the_ptr_vector;
you can pass &the_ptr_vector[0]. This will be of type int** and is
guaranteed to work since std::vector is guaranteed to be contiguous.
Is something like this simple array of int pointers example correct?
class A
{
public:
A()
{
// I know I need 3 pointers to integers here
m_integers = new int * [3];
m_integers[0] = new int(1);
m_integers[1] = new int(2);
m_integers[2] = new int(3);
}
private:
int ** m_integers
};
It is correct (in that it will do the expected if nothing bad happens), b=
ut
not exception safe (i.e., it will do bad things if something bad happens
elsewhere): if one of the the lines
new int (...)
throws, then memory will leak.
It is actually a little difficult to manage containers of pointers so tha=
t
nothing bad can happen. I think, the following will do, but I did not thi=
nk
through all the possible mishaps.
#include <vector>
class auto_ptr_vector : private std::vector<int*> {
typedef std::vector<int*> base;
public:
using base::operator[];
using base::at;
using base::begin;
using base::end;
auto_ptr_vector ( base::size_type n )
: base ( n, 0 )
{}
~auto_ptr_vector ( void ) {
for ( base::size_type n = 0; n < this->size(); ++n ) {
delete (*this)[n];
}
}
};
class A {
public:
A()
: m_integers ( 3 )
{
m_integers[0] = new int(1);
m_integers[1] = new int(2);
m_integers[2] = new int(3);
}
private:
auto_ptr_vector m_integers;
};
Again, you can use the API via &m_integers[0].
Best
Kai-Uwe Bux
This is really a terrible idea, why break the rule? The rule, of
course being, NEVER USE AN AUTO_PTR IN A CONTAINER. While it might be
possible to get it to work under really limited circumstances, do you
really want to have to remember what those circumstances are? And
what if later you realize you need to be able to use the push_back
method, and then forget that it's going to screw up the auto_ptr's due
to reallocation? What happens if you called std::swap() on two
iterators from auto_ptr_vector above? What if you use the above
auto_ptr_vector in an algorithm such as sort? Can you really
guarantee that not only will reallocation never occur, but an element
is never even -copied-?
If the "loop-through-and-delete-container-pointers-in-destructor" is
not good enough with a container of raw pointers, then download boost,
and use boost::shared_ptr<>.