【问题标题】:problems with dynamic_castdynamic_cast 的问题
【发布时间】:2010-06-19 16:23:41
【问题描述】:

我有这个sn-p的代码:

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

【问题讨论】:

    标签: c++ casting shared-ptr


    【解决方案1】:

    shared_ptr 不会隐式转换为指针——它是一个类类型的对象——并且dynamic_caststatic_castconst_cast 都只对指针进行操作。

    虽然您可以在shared_ptr&lt;T&gt;::get() 上使用dynamic_cast,但最好使用dynamic_pointer_cast&lt;FamilyLine&gt;(),否则您可能会不小心引入双deletes:

    回报:
    * 当dynamic_cast&lt;T*&gt;(r.get()) 返回一个非零值时,一个shared_ptr&lt;T&gt; 对象存储它的副本并与r 共享所有权;
    * 否则,一个空的 shared_ptr&lt;T&gt; 对象。
    [...]
    注意:看似等价的表达方式

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

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

    例如:

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

    【讨论】:

    • @hello:你使用的是什么版本,TR1 et al(使用&lt;memory&gt;)还是boost(&lt;boost/pointer_cast.hpp&gt;)? (旁注:帖子的所有者总是会收到 cmets 通知,因此在这种情况下不需要 @user 语法)
    • 那么您可能正在使用 TR1 或 C++0x 功能,#include &lt;memory&gt; 应该足够了。
    • 好吧,每个值得一提的 C++ 库要么在命名空间中拥有其类型和函数(例如标准库的 std,Boost 的 boost,...),要么至少提供它们一个公共前缀(Q 用于 Qt)。因此,只要您在任何地方都没有针对 boost 的 using 指令,而是针对 std 使用指令,那么 shared_ptr 必须来自标准库或其扩展。顺便说一下,这种混淆是反对将using namespace foo; 到处乱放的一个很好的论据。
    • @hello:你有#include &lt;memory&gt;吗?您是否对shared_ptr 使用任何特殊包含(即除了&lt;memory&gt;)?
    • 啊哈,shared_ptr.h 是什么?这是哪里来的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多