Re: pointer to an array of pointers - allocate
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), but
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 that
nothing bad can happen. I think, the following will do, but I did not think
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