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) 。 –