STL的容器具有託管對象的能力,前提是將對象插入容器的時候需要傳入對象,而不能是指向對象的指針。示例代碼如下:
#include <iostream>
#include <vector>
using namespace std;
class Animal{
public:
Animal(string name):_name(name) {cout << "Construct " << _name << endl;}
~Animal() {cout << "Deconstruct " << _name << endl;}
private:
string _name;
};
int main()
{
Animal *ani = new Animal("Cat");
vector<Animal> vec;
vec.push_back(*ani);
Animal *ani1 = new Animal("Dog");
vector<Animal*> ptr_vec;
ptr_vec.push_back(ani1);
return 0;
}
編譯運行上面的程序,Output如下:
Construct Cat
Construct Dog
Deconstruct Cat
表明如果插入vector容器中的是對象指針的話,new生成的對象不會被vector託管,這時內存需要自己進行釋放。