Search code examples
c++c++11vectorreference-wrapper

Transform std:vector<reference_wrapper<Base>> to std:vector<reference_wrapper<Derived>> Runtime error time: 0 memory: 3412 signal:6


I am trying to convert vector of references to Base objects to vector of references to Derived objects. Everything is compiling fine, but i got this error: Runtime error time: 0 memory: 3412 signal:6

This is my code:

#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;
}

What is wrong with dynamicCast() function?

EDIT: @John Zwinck answer helped, but when i try to do this in my code i got compilation error:

cannot dynamic_cast '(& obj)->std::reference_wrapper<_Tp>::get()' (of type 'class MEPObject') to type 'class MEPGene&' (target is not pointer or reference to complete type) 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()));
    }
}
                                                      ^

Solution

  • Nothing is wrong with dynamicCast(). The problem is here:

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

    You only ever construct instances of B which is the base class. You can't possibly cast them to D which is the derived class.

    Perhaps you meant to construct derived instances and store them in your vector of references to base.