The shared_ptrs vector behaves mysteriously

I created a Baseclass vector shared_ptrto store Derivedclass shared_ptrs and run into some problems.

The following simplified example shows what is happening.

#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.

+4
source share
1 answer

It is also verified that the first element is destroyed. The original bug report is here .

It seems that under certain circumstances, you initialize a vector with a list of initializers. And their answer wasThe fix should show up in the **future release** of Visual C++.

+6

Source: https://habr.com/ru/post/1529807/


All Articles