2014-03-03 36 views
4

我创建了一个向量Baseshared_ptr s举行Derivedshared_ptr s,并遇到一些问题。向量的shared_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; 
} 

当我在我的机器(64位的Win7用MS VS2013)我得到以下输出上运行此:

5 
99 
18 

5 
99 
18 

-572662307 
99 
18 

缺少什么我在这里?

谢谢。

+0

[在gcc 4.8.1上正常工作](https://ideone.com/OPnVoS) – interjay

+0

据我所知,您发布的输出不符合输出的码。我将你的代码复制到ideone并且输出是正确的(请参阅https://ideone.com/2Y33lW)。 – utnapistim

+3

看起来像你击中[这个bug](http://www.beta.microsoft.com/VisualStudio/feedback/details/814697/first-element-of-vector-is-destroyed-initializing-from-initializer-list) 。 –

回答

6

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

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

+0

谢谢!我一直在敲我的头:) –