I am trying to initialize a vector of shared pointers to base class with a number of shared pointers to derived class, using brace initialization. The code (after stripping out irrelevant details) looks like this:
#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;
}
}
When I compile this code under Visual Studio 2013 and run it in the console, the result is:
Without brace initialization:
0.1
0.2
0.3
With brace initialization:
7.52016e-310
and then the program crashes. Is this to be expected and brace initialization is incompatible with implict conversion of std::shared_ptr<Derived>
to std::shared_ptr<Base>
, or is that a bug in the Visual Studio? Does brace initialization do some magic under the hood which blocks the shared pointer conversion (e.g. taking references to pointers)?