4
我創建了一個向量Base
類shared_ptr
s舉行Derived
類shared_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
缺少什麼我在這裏?
謝謝。
[在gcc 4.8.1上正常工作](https://ideone.com/OPnVoS) – interjay
據我所知,您發佈的輸出不符合輸出的碼。我將你的代碼複製到ideone並且輸出是正確的(請參閱https://ideone.com/2Y33lW)。 – utnapistim
看起來像你擊中[這個bug](http://www.beta.microsoft.com/VisualStudio/feedback/details/814697/first-element-of-vector-is-destroyed-initializing-from-initializer-list) 。 –