Ste*_*att 4 c++ inheritance pointers vector shared-ptr
我创建了一个Base类shared_ptrs 的向量来保存Derived类shared_ptr,并遇到一些问题.
以下简化示例显示了会发生什么.
#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;
}
Run Code Online (Sandbox Code Playgroud)
当我在我的机器上运行它(带有MS VS2013的Win7 64位)时,我得到以下输出:
5
99
18
5
99
18
-572662307
99
18
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么?
谢谢.
在这里验证它,第一个元素被摧毁.在原来的bug报告是在这里.
在某些情况下,使用初始化列表初始化向量时,似乎会发生这种情况.他们的反应是The fix should show up in the **future release** of Visual C++.