【问题标题】:Vector of shared_ptrs behaves mysteriouslyshared_ptrs 的向量表现得很神秘
【发布时间】:2014-03-03 14:37:21
【问题描述】:

我创建了一个Baseshared_ptrs 的向量来保存Derivedshared_ptrs,但遇到了一些问题。

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

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

当我在我的机器(Win7 64bit with MS VS2013)上运行它时,我得到以下输出:

5
99
18

5
99
18

-572662307
99
18

我在这里错过了什么?

谢谢。

【问题讨论】:

  • 据我所知,您发布的输出与代码的输出不对应。我将您的代码复制到 ideone 并且输出正确(请参阅ideone.com/2Y33lW)。
  • 看起来你点击了this bug
  • 这很奇怪。即使没有虚拟析构函数,它也应该可以工作。但是您可以尝试向Base 添加一个空的虚拟析构函数吗?

标签: c++ pointers inheritance vector shared-ptr


【解决方案1】:

这里也验证了,第一个元素被破坏了。 original bug report is here

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

【讨论】:

  • 谢谢!我一直在努力解决这个问题:)
猜你喜欢
  • 1970-01-01
  • 2018-12-14
  • 2014-06-05
  • 2023-03-25
  • 1970-01-01
  • 2020-06-20
  • 2019-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多