オブジェクトをベクトルに直接格納せず、代わりに実際のオブジェクト自体へのポインター/参照を使用することで、Python と同じ方法でこれを行うことができます。
#include <memory>
typedef std::vector<std::unique_ptr<A>> AVector;
この場合、ポリモーフィズムが許可され、A から派生したものへのポインターをプッシュできます。
あなたが試みようとしていた場合、あなたは丸いペグを四角い穴に合わせようとしていました. std::vector は、実際にはメモリ メンバーの大きなブロック * sizeof(T) を割り当てるコードの単純なラッパーです。
「unique_ptr」はポインター用の C++11 コンテナーであり、ポインターがなくなると削除することを認識しています。C++11/C++0x をサポートしていない場合は、ポインターを使用するか、独自の「自動」ポインター ラッパーを作成できます。
// Old-style pointer
typedef std::vector<A*> AVector;
AVector avec;
avec.push_back(new A);
avec.push_back(new B);
avec.push_back(new A);
avec.push_back(new B);
// now it's your responsibility to 'delete' these allocations when you remove them.
void discardAvec(size_t position) {
A* ptr = avec[position];
delete ptr;
avec.erase(avec.begin() + position);
}
ideone.com で、以下のウォークスルーのライブ デモを参照してください。
#include <iostream>
#include <memory>
#include <vector>
typedef std::vector<class A*> AVector;
class A
{
protected: // so B can access it.
int m_i;
public:
A(int i_) : m_i(i_)
{
std::cout << "CTor'd A(i) " << (void*)this
<< " with " << m_i << std::endl;
}
A(int i_, bool) : m_i(i_)
{
std::cout << "CTor'd A(i, b) " << (void*)this
<< " with " << m_i << std::endl;
}
virtual ~A()
{
std::cout << "DTor'd A " << (void*)this << " with " << m_i << std::endl;
}
};
class B : public A
{
int m_j;
public:
B(int i_, int j_) : A(i_, true), m_j(j_)
{
std::cout << "CTor'd B(i, j) " << (void*)this
<< " with " << m_i << ", " << m_j << std::endl;
}
virtual ~B()
{
std::cout << "DTor'd B " << (void*)this
<< " with " << m_i << ", " << m_j << std::endl;
}
};
int main()
{
AVector avec;
std::cout << "create A(1)" << std::endl;
avec.push_back(new A(1)); // allocated an "A" on the heap.
std::cout << "create B(2, 1)" << std::endl;
avec.push_back(new B(2, 1)); // allocated a "B" on the heap.
std::cout << "create B(2, 2)" << std::endl;
avec.push_back(new B(2, 2));
std::cout << "create A(3) " << std::endl;
avec.push_back(new A(3));
std::cout << "populated avec" << std::endl;
A* ptr = avec[2]; // take the pointer of what is actually a B
avec.erase(avec.begin() + 2); // remove it from the vector.
std::cout << "removed entry 2 from the vector" << std::endl;
// 'ptr' is still valid because it's an allocation, and C++ doesn't
// garbage collect heap allocations. We have to 'delete' it ourselves.
// Also note that because A and B have virtual destructors,
// you will see both of them called.
delete ptr;
// Now watch what DOESN'T happen as we exit.
// everything we CTOR'd that doesn't get DTORd is a leak.
return 0;
}