ブレースの初期化を使用して、派生クラスへの多数の共有ポインターを使用して、基本クラスへの共有ポインターのベクトルを初期化しようとしています。コードは (無関係な詳細を取り除いた後) 次のようになります。
#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
その後、プログラムがクラッシュします。std::shared_ptr<Derived>
これは予想されることであり、ブレースの初期化はへの暗黙の変換と互換性がありませんstd::shared_ptr<Base>
か、それとも Visual Studio のバグですか? ブレースの初期化は、内部で共有ポインターの変換をブロックする魔法を行いますか (ポインターへの参照の取得など)?