If you need a polymorphic container, that is a vector that can hold CCSprites or any derived class, then you can use a std::vector<std::unique_ptr<CCSprite>>
to describe this and provide you with you with lifetime management of the classes.
#include <memory>
#include <vector>
#include <iostream>
using namespace std;
class Foo {
int m_i;
public:
Foo(int i_) : m_i(i_) { cout << "Foo " << m_i << " ctor" << endl; }
~Foo() { cout << "Foo " << m_i << " ~tor" << endl; }
};
class FooBar : public Foo {
public:
FooBar(int i_) : Foo(i_) { cout << "FooBar " << m_i << " ctor" << endl; }
~FooBar() { cout << "FooBar " << m_i << " ~tor" << endl; }
};
int main(int argc, const char** argv) {
vector<unique_ptr<Foo>> foos;
Foo foo(1);
foos.emplace_back(unique_ptr<Foo>(new Foo(2)));
cout << "foos size at end: " << foos.size() << endl;
return 0;
}
(I tried adding an example of a short scoped unique_ptr being added to the vector but it caused my GCC 4.7.3 to crash when testing)
Foo 1 ctor
Foo 2 ctor
foos size at end: 1
[<-- exit happens here]
Foo 1 dtor
Foo 2 dtor
If you don't need a polymorphic container, then you can avoid the memory management overhead by just having the vector directly contain the CCSprite objects. The disadvantage to this approach is that the address of given sprites can change if you add/remove elements. If the object is non-trivial this can quickly get very expensive:
std::vector<CCSprite> sprites;
sprites.emplace_back(/* args */);
CCSprite* const first = &sprites.front();
for (size_t i = 0; i < 128; ++i) {
sprites.emplace_back(/* args */);
}
assert(first == &sprites.front()); // probably fires.