2014-03-03 34 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

謝謝!我一直在敲我的頭:) –