我正在尝试使用大括号初始化,使用多个指向派生类的共享指针来初始化指向基类的共享指针向量。代码(去除不相关的细节后)如下所示:
#include <vector>
#include <memory>
#include <iostream>
struct Base {
Base(double xx) { x = xx; }
virtual ~Base() {}
double x;
};
struct Derived : public Base {
Derived(double xx) : Base(xx) {}
};
int main(void) {
std::vector<std::shared_ptr<Base>> v = {
std::make_shared<Derived>(0.1),
std::make_shared<Derived>(0.2),
std::make_shared<Derived>(0.3)
};
std::vector<std::shared_ptr<Base>> v4(3);
v4[0] = std::make_shared<Derived>(0.1);
v4[1] = std::make_shared<Derived>(0.2);
v4[2] = std::make_shared<Derived>(0.3);
std::cout << "Without brace initialization: " << std::endl;
for (auto x : v4) {
std::cout << x->x << std::endl;
}
std::cout << "With brace initialization: " << std::endl;
for (auto x : v) {
std::cout << x->x << std::endl;
}
}
当我在 Visual Studio 2013 下编译这段代码并在控制台中运行它时,结果是:
Without brace initialization:
0.1
0.2
0.3
With brace initialization:
7.52016e-310
然后程序崩溃。这是意料之中的,大括号初始化与 to 的隐式转换不兼容std::shared_ptr<Derived>
,std::shared_ptr<Base>
还是 Visual Studio 中的错误?大括号初始化是否在幕后做了一些魔术,阻止了共享指针转换(例如,引用指针)?