变换std:vector <reference_wrapper <base>&gt;到std:vector <reference_wrapper <derived>&gt;运行时错误时间:0内存:3412信号:6

时间:2016-08-02 21:33:54

标签: c++ c++11 vector reference-wrapper

我试图将Base对象的引用向量转换为Derived对象的引用向量。一切都编译得很好,但我得到了这个错误:运行时错误时间:0内存:3412信号:6

这是我的代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

struct B {
    B(int i) { b = i; }
    virtual ~B() {}
    int b;
};

struct D: public B {
    D(int i): B(i) {}
};

typedef vector<reference_wrapper<B>> refB;
typedef vector<reference_wrapper<D>> refD;

void dynamicCast(refB &b, refD &d)
{
    for(const auto& bb: b)
    {
        d.push_back(dynamic_cast<D&> (bb.get()));
    }
}

int main() {
    vector<B*> numbers;
    refB refNumbers;
    refD dNumbers;

    for(int i = 0; i < 10; i++)
    {
        numbers.push_back(new B(2*i));
        refNumbers.push_back(*numbers[i]);
    }

    dynamicCast(refNumbers, dNumbers);

    return 0;
}

dynamicCast()函数有什么问题?

编辑: @John Zwinck回答有帮助,但当我尝试在我的代码中执行此操作时出现编译错误:

  

不能dynamic_cast&#39;(&amp;   OBJ) - &GT;的std ::的reference_wrapper&LT; _TP&GT; ::得到()&#39; (类型&#39;类   MEPObject&#39;)键入&#39;类MEPGene&amp;&#39; (目标不是指针或   参考完整类型)            genes.push_back(dynamic_cast(obj.get()));

class MEPObject;
class MEPGene;
typedef std::vector<std::reference_wrapper<MEPObject>> MEPObjects;
typedef std::vector<std::reference_wrapper<MEPGene>> MEPGenes;

void dynamicCast(MEPObjects &objects, MEPGenes &genes)
{
    for(const auto &obj: objects)
    {
        genes.push_back(dynamic_cast<MEPGene&> (obj.get()));
    }
}
                                                      ^

1 个答案:

答案 0 :(得分:2)

dynamicCast()没有错。问题出在这里:

    numbers.push_back(new B(2*i));

您只构造B的基类的实例。您无法将它们转换为派生类D

也许你打算构造派生实例并将它们存储在base的引用向量中。