has*_*svn 2 c++ exception shared-ptr
好吧,我被告知这个问题:为什么你可以抛出指向派生类的指针并捕获指向其基础的指针......但你不能用shared_ptrs做到这一点?
例如,这有效:
class Base {};
class Derived : public Base {};
int main()
{
try
{
throw new Derived() ;
}
catch( const Base2 * b )
{
printf("Received a base" ) ;
}
return 0 ;
}
Run Code Online (Sandbox Code Playgroud)
但事实并非如此
int main()
{
try
{
throw std::tr1::shared_ptr<Derived>( new Derived() ) ;
}
catch( const std::tr1::shared_ptr<Base> & b )
{
printf("Received a base" ) ;
}
return 0 ;
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
原因很简单:即使derived
与之相关base
,shared_ptr<derived>
也与之无关,shared_ptr<base>
除非模板明确地提供它,否则没有从一个到另一个的隐式转换(并且同样适用于以相同方式实例化的任何其他模板).
但是,对于例外情况,我不确定您真正想要解决的问题.通常,您想要抛出一个对象(而不是指针),并且您想要捕获一个const
引用.由于你没有任何实际可能有多个指向同一个异常对象的指针,我不确定你用什么问题来解决shared_ptr<exception_object>
.