dynamic_cast的问题

时间:2010-06-19 16:23:41

标签: c++ casting shared-ptr

我有这段代码:

void addLineRelative(LineNumber number, LineNumber relativeNumber) {
            list<shared_ptr<Line> >::iterator i;
            findLine(i, number);
            if(i == listOfLines.end()){
                throw "LineDoesNotExist";
            }

   line 15  if(dynamic_cast<shared_ptr<FamilyLine> >(*i)){
                cout << "Family Line";
            } else {
                throw "Not A Family Line";
            }
        }

我有类Line并从它派生FamilyLine和RegularLine,所以我想找到FamilyLine

我的程序在第15行失败,我收到错误

cannot dynamic_cast target is not pointer or reference

有人可以帮助,提前谢谢

编辑

我试过这个:

shared_ptr<FamilyLine> ptr(dynamic_cast<shared_ptr<FamilyLine> >(*i));
if(ptr){
    //do stuff
}

同样的错误

编辑

void addLineRelative(LineNumber number, LineNumber relativeNumber) {
        list<shared_ptr<Line> >::iterator i;
        findLine(i, number);
        if(i == listOfLines.end()){
            throw "LineDoesNotExist";
        }

        shared_ptr<FamilyLine> ptr(dynamic_pointer_cast<FamilyLine>(*i));
        if (ptr){
            cout << "Family Line";
        } else {
            throw "Not A Family Line";
        }
    }

收到此错误

Multiple markers at this line
    - `dynamic_pointer_cast' was not declared in this 
     scope
    - unused variable 'dynamic_pointer_cast'
    - expected primary-expression before '>' token

1 个答案:

答案 0 :(得分:4)

shared_ptr不会隐式转换为指针 - 它是类型对象 - 而dynamic_caststatic_castconst_cast都只对指针进行操作。

虽然您可以在dynamic_cast上使用shared_ptr<T>::get(),但最好使用dynamic_pointer_cast<FamilyLine>(),否则您可能会意外地引入双重delete

  

<强>返回:
   *当dynamic_cast<T*>(r.get())返回非零值时,shared_ptr<T>对象存储其副本并与r共享所有权;
   *否则为空shared_ptr<T>个对象   [...]
  注意:看似相同的表达式

shared_ptr<T>(dynamic_cast<T*>(r.get()))
  

最终会导致未定义的行为,尝试两次删除同一个对象。

E.g:

shared_ptr<FamilyLine> ptr(dynamic_pointer_cast<FamilyLine>(*i));
if (ptr) {
    // ... do stuff with ptr
}