C++中句柄(二)
#include
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector vec;
helloA a;
helloB b;
sample sample1(a);
sample sample2(b);
vec.push_back(sample1);
vec.push_back(sample2);
for ( vector::iterator iter=vec.begin();iter!=vec.end();iter++)
{
(*iter)->func();
}
return 0;
}
我们得到了正确的输出,如同shared_ptr,我们引入了计数,在vec生命周期结束时,我们不需要自己释放内存。
对上面代码需要注意,为什么克隆函数,要用virtual helloA* clone() const {return new A(*this);}而不是直接virtual A*clone() const {return this;}
因为,这样潜在一个问题,比如
helloB b;
sample sam(b);
vec.push_back(sam);
当b的生命周期结束,而vec的生命周期尚未结束时,调用(*iter)->A.func();就会出错,而更直接的是,这样做与直接用指针进行多态没有太大区别了。