Abhra Basak
Abhra Basak

Reputation: 412

C++11 indexing vector of smart pointers as member of a class

I have the following classes in my project: Neuron, ActivationNeuron, Layer, and ActivationLayer as partly mentioned below.

class Neuron { }; /* abstract class */
class ActivationNeuron : public Neuron { };

class Layer {
protected:
    vector<shared_ptr<Neuron>> neurons;
public:
    Neuron& operator[](const int index) {
        return *this->neurons[index];
    }
};

class ActivationLayer : public Layer {
public:
    ActivationNeuron& operator[](const int index) {
        return *static_pointer_cast<ActivationNeuron>(this->neurons[index]);
    }
};

I have the following two questions:

I also welcome improvements to my current implementation.

Upvotes: 0

Views: 600

Answers (1)

Sorin
Sorin

Reputation: 11968

According to http://www.cplusplus.com/reference/memory/static_pointer_cast/ what you have is equivalent to

return *static_cast<ActivationNeuron*>(this->neurons[index].get());

The statement above will work for unique_ptr as well.

On the semantics side, you are changing the ownership model. Before anybody could hold on to the pointers. Now they will be bound to Layer. If all usage is while Layer exists it should be fine. If you need some components to access the data after Layer is destroyed (like deferred logging) then you will run into problems.

Not knowing the larger application is hard to say if there's any issue.

Performance wise: the static cast, indexing and the .get() are almost trivial (O(1) complexity, just memory indexing) and I wouldn't worry too much about their performance. You can do a profile to make sure that this is the case in your application. You are definitely only marginally worse as compared to vector<Neuron*>.

Upvotes: 2

Related Questions