shared_ptrs的矢量行为神秘

Vector of shared_ptrs behaves mysteriously

本文关键字:ptrs shared      更新时间:2023-10-16

我创建了一个类Base shared_ptr的向量来保存Derivedshared_ptr s,并遇到了一些问题。

以下简化示例显示了发生的情况。

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

当我在我的机器上运行它(带有 MS VS7 的 Win7 64 位)时,我得到以下输出:

5
99
18
5
99
18
-572662307
99
18

我在这里错过了什么?

谢谢。

在这里也验证了,第一个元素被销毁了。原始错误报告在这里。

在某些情况下,当您使用初始值设定项列表初始化向量时,似乎会发生这种情况。他们的反应是The fix should show up in the **future release** of Visual C++.