Before I start with my question, let me say that I know that I can solve my problem easily using the standard library or gsl library (e.g. std::Vector
). But I'm trying to learn C++ and dynamic memory allocation, so I would like to know if there is a way to solve it without using a Vector or anything similar.
I have a Layer
class that contains a number of neurons determined when the object is created (through dynamic memory allocation):
class Layer {
private:
unsigned int _size;
const Neuron* _neurons;
public:
Layer(unsigned int size);
~Layer();
const Neuron* getNeuron(unsigned int index) const;
};
Layer::Layer(unsigned int size) {
_size = size;
_neurons = new Neuron[size];
}
const Neuron* Layer::getNeuron(unsigned int index) const {
Expects(index < _size);
return &_neurons[index];
}
Layer::~Layer() {
delete[] _neurons;
}
Now the challenge is in the Network
class: I need to create a Network of n layers, each containing a different number of neurons (passed as an array of length n):
class Network {
private:
unsigned int _nb_layers;
const Layer* _layers;
public:
Network(unsigned int nb_layers, unsigned int* nb_neurons);
~Network();
const Layer* getLayer(unsigned int index) const;
};
Network::Network(unsigned int nb_layers, unsigned int *nb_neurons) {
_nb_layers = nb_layers;
_layers = new Layer[nb_layers];
for(int i = 0; i < nb_layers; i++) {
_layers[i] = new Layer(nb_neurons[i]);
}
}
const Layer* Network::getLayer(unsigned int index) const {
Expects(index < _nb_layers);
return &_layers[index];
}
Network::~Network() {
delete _layers;
}
The problem is that the Network constructor fails, because _layers = new Layer[nb_layers]
tries to call the constructor with no parameters, which fails.
Also, _layers[i] = new Layer(nb_neurons[i])
fails because "No viable overloaded '='", which I do not understand.
How can I fix this using dynamic memory allocation instead of std::Vector
?
Finally, is the way I implemented dynamic memory allocation correct and without any memory leak? I'm wondering what happens to my unsigned int *nb_neurons
in the Network constructor since the values are being used but I'm never deleting it.
(As a background, I'm been coding in Java, Python and PHP for years)
Thank you very much!