1.多态下使用
class parent
{
public:
parent()
{
cout << "parent constructor" << endl;
}
virtual void showinfo()
{
cout << "parent info" << endl;
}
~parent()
{
cout << "parent destructor" << endl;
}
};
class child : public parent
{
public:
child()
{
cout << "child constructor" << endl;
}
virtual void showinfo()
{
cout << "child info" << endl;
}
~child()
{
cout << "child destructor" << endl;
}
};
int main()
{
shared_ptr<parent> sp = make_shared<child>();
sp->showinfo();
return 0;
}
运行程序,输出为:
parent constructor
child constructor
child info
child destructor
parent destructor
转载自:http://cache.baiducontent.com/c?m=9d78d513d99256af28fa940e1a16a6716f50971239c0a11368a2e25f92144c37437193b130541713a4b56b6671b83958fd873465467237c4eadccf0a83b4c86e69ca303503019b114c8e4cb8cb31748076cc4de9d845b0fced77caefd1d8d55f50ca500267d3b0cd01514a9d72a64377b0fdc709085812b1e63364fb53&p=8970ce0c85cc43eb2abd9b7d0d1c80&newp=8b2a9715d9c041a51afb8e2f470ec4231610db2151d6da01298ffe0cc4241a1a1a3aecbf26241504d6c37c610aab435beefb3275340234f1f689df08d2ecce7e&user=baidu&fm=sc&query=c%2B%2B+%D6%C7%C4%DC%D6%B8%D5%EB%B6%E0%CC%AC&qid=d66557ba00001946&p1=1
2.多态下类型转换 在编写基于虚函数的多态代码时,指针的类型转换很有用,比如把一个基类指针转型为一个子类指针或者反过来。但是对于share_ptr不能使用诸如static_cast<T*>(p.get())的形式,这将导致转型后的指针无法再被shared_ptr正确管理。为了支持这样的用法,shared_ptr提供了类似的转型函数 static_pointer_cast<T>()、const_pointer_cast<T>()、dynamic_pointer_cast<T>(),它们与标准的转型操作符static_cast<T>()、const_cast<T>()和dynamic_cast<T>()类似,但返回的转型后的shared_ptr。
例如,下面的代码使用
dynamic_pointer_cast<T>()把一个shared_ptr<std::exception>向下转型为一个
shared_ptr<std::exception>,然后又用
static_pointer_cast<T>()重新转为
shared_ptr<std::exception>:
- shared_ptr<std::exception> sp1(new bad_exception("error"));
- shared_ptr<bad_exception> sp2 = dynamic_pointer_cast<bad_exception>(sp1);
- shared_ptr<std::exception> sp3 = static_pointer_cast<std::exception>(sp2);
- assert(sp3 == sp1);
转载自:http://blog.csdn.net/bopzhou/article/details/6748763