Question

I created a vector of Base class shared_ptrs to hold Derived class shared_ptrs, and running into some problems.

The following simplified example shows what happens.

#include <iostream>
#include <memory>
#include <vector>

using namespace std;

class Base {
public:
    Base(int i) : val(i) {}
    int val;
};

class Derived : public Base {
  public:
    Derived(int i) : Base(i) {}  
};

int main()
{
    vector<shared_ptr<Base>> vec1{
        make_shared<Base>(5),
        make_shared<Base>(99),
        make_shared<Base>(18)};

    for (auto const e : vec1)
        cout << e->val << endl;
    cout << endl;

    vector<shared_ptr<Derived>> vec2{
        make_shared<Derived>(5),
        make_shared<Derived>(99),
        make_shared<Derived>(18)};

    for (auto const e : vec2)
        cout << e->val << endl;
    cout << endl;

    vector<shared_ptr<Base>> vec3{
        make_shared<Derived>(5),
        make_shared<Derived>(99),
        make_shared<Derived>(18)};

    for (auto const e : vec3)
        cout << e->val << endl;
    cout << endl;

    return 0;
}

When I run this on my machine (Win7 64bit with MS VS2013) I get the following output:

5
99
18

5
99
18

-572662307
99
18

What am I missing here?

Thank you.

Was it helpful?

Solution

Verified it here too, the first element is getting destroyed. The original bug report is here.

It seems to happen when you initialize a vector with an initializer list in certain circumstances. And their response was The fix should show up in the **future release** of Visual C++.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top