想不到,智能指针也可以实现运行多态,。下面展示了个小例子。
#include<iostream>
#include<memory>
using namespace std;
class P
{
public:
P()
{ cout<<"P construction"<<endl; }
virtual void f(int t)
{ cout <<"P!!"<<",t="<<t<<endl; }
~P()
{ cout<<"P destroy"<<endl; }
};
class C1 :public P
{
public:
C1()
{ cout<<"C1 construction"<<endl; }
void f(int t)
{ cout <<"C1!!"<<",t="<<t<<endl; }
~C1()
{ cout<<"C1 destroy"<<endl; }
};
class C2 : public P
{
public:
C2()
{ cout<<"C2 construction"<<endl; }
void f(int t)
{ cout <<"C2!!"<<",t="<<t<<endl; }
~C2()
{ cout<<"C2 destroy"<<endl; }
};
void test1(int t)
{
这里需要预先生成所有的字对象,这是不优美的
C1 myc1;
C2 myc2;
P * myp = NULL;
cout<<"test1 start..."<<endl;
if(t>5)
{ myp = &myc1; }
else
{ myp = &myc2; }
myp->f(t);
}
void test2(int t)
{
///这里按需new子对象,切无须担心内存释放
std::tr1::shared_ptr<P> myPtr;
cout<<"test2 start..."<<endl;
if(t>5)
{
//下面这种方式会生成临时一个智能指针,不是很安全
myPtr = std::tr1::shared_ptr<P>(new C1);
}
else
{
///给每个智能指针都起一个名字会安全得多
std::tr1::shared_ptr<P> C2Ptr(new C2);
myPtr = C2Ptr;
}
myPtr->f(t);//
}
int main()
{
test1(2);
test1(20);
cout<<"====================="<<endl;
test2(2);
test2(20);
}
结果如下: