shared_ptrs的矢量行为神秘
Vector of shared_ptrs behaves mysteriously
我创建了一个类Base
shared_ptr
的向量来保存Derived
类shared_ptr
s,并遇到了一些问题。
以下简化示例显示了发生的情况。
#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;
}
当我在我的机器上运行它(带有 MS VS7 的 Win7 64 位)时,我得到以下输出:
5
99
18
5
99
18
-572662307
99
18
我在这里错过了什么?
谢谢。
在这里也验证了,第一个元素被销毁了。原始错误报告在这里。
在某些情况下,当您使用初始值设定项列表初始化向量时,似乎会发生这种情况。他们的反应是The fix should show up in the **future release** of Visual C++.
相关文章:
- 引用 std::shared:ptr 以避免引用计数
- dopen():不以 root 身份运行时"failed to map segment from shared object"
- 无法使用 libtool 将 -shared 参数传递给 g++
- 链接 boost 库时"Error while loading shared libraries"引发的,除了我无法使用 root 访问权限来修复它
- 将共享 ptrs 设置为空
- 解决方法:'can not be used when making a shared object; recompile with -fPIC'使用Cmake。使用普通的 g++ 工作
- gcc -fPIC vs. -shared
- 在shared_from_this()中的错误类型(在继承类中)(是否有dyn.type-ware shared Poi
- 如何将函数 ptr 分配给函数 ptrs 数组(Arduino C++)
- "directory containing symbolic versions of my app's shared libraries"的位置(ndk-stack)
- Qt自定义插件无法加载 - "Shared Library Not Found"
- C - Shared Library - dlopen, dlsym
- ubuntu 12.04 中的 openCV 程序编译错误"libopencv_core.so.2.4: cannot open shared object file: No such file or
- boost::shared_ptr和std::shared-ptr的同居
- 将GoogleMock与Boost::Shared Pointers一起使用时泄漏的Mock对象
- Singleton: C++ shared dll
- Boost Python , python functions and ptrs
- 传递"shared"指针的 OpenMP 任务
- 如何将参数push_back unique_ptr到共享 ptrs 的向量上
- "int *(&arry)[10] = ptrs;"的含义是什么?你怎么读这样的东西?