支持初始化并从派生到基类转换共享指针

时间:2014-04-20 23:37:09

标签: c++11 visual-studio-2013 shared-ptr make-shared list-initialization

我正在尝试使用大括号初始化初始化一个共享指向基类的向量,其中包含一些指向派生类的共享指针。代码(在删除不相关的细节之后)看起来像这样:

#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中的错误?大括号初始化是否会阻止共享指针转换(例如引用指针)?

0 个答案:

没有答案