0

I want a vector to hold pointers to some objects that it will own.

Here is the vector:

private: std::vector<fppVirtual*> m_fapps;

I have created elements like this:

    m_fapps.push_back(new fpp1(renderingEngine)); //fpp* are subclasses of fppVirtual
    m_fapps.push_back(new fpp2(renderingEngine));
    m_fapps.push_back(new fpp3(renderingEngine));

As m_fapps is a vector instance variable in another class, I want to make sure that class's destructor properly cleans up m_fapps:

       for (int i=0, size=m_fapps.size();i<size;++i){
        delete m_fapps[i];
       }

Is this acceptable memory management technique? I assume this loop is needed since when the vector goes out of scope when its owning class is destructed, only pointers to these new objects will be removed, right?

johnbakers
  • 24,158
  • 24
  • 130
  • 258

3 Answers3

3

This works (with a few caveats) but is not considered idiomatic C++, for good reason.

You should strongly consider using a vector of smart pointers (or a smart vector like boost::ptr_vector) instead, in order to avoid having to do manual memory management.

This would also give you exception safety for free, and would also avoid nasty ownership issues that occur if your outer class is copyable.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • i'm inclined to agree with the other suggestion that `vector>` is a natural fit for this if I have no other reason to include boost in my project – johnbakers Apr 05 '13 at 06:48
  • 1
    @SebbyJohanns: Once you look into Boost a bit more, I am sure you will find plenty of reasons to include it in your project. – Björn Pollex Apr 05 '13 at 06:48
  • @SebbyJohanns: sure, there are now a number of smart pointer types in the standard library, pick the one that best suits your use-case. – Oliver Charlesworth Apr 05 '13 at 06:51
2

As no one gave you straight forward answer yet - yes, it is acceptable and this is the only way to free this memory, having this declaration of the vector.

This can and should be avoided, using smart pointers, as @OliCharlesworth suggested or using some other container, ponited by @BjörnPollex.

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
1

You should use boost::ptr_vector instead. The interface is the same, but it handles memory management for you. See this question for some guidelines about whether to use ptr_vector or vector<shared_ptr<>>.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283