C ++:如何初始化以下std :: shared_ptr构造函数数组

时间:2018-04-08 14:02:43

标签: c++ class pointers shared-ptr smart-pointers

我有一个名为Base的抽象类,我从中派生了一个类(Derived),如下所示:

#include <iostream>
#include <string>
#include <memory>

class Base
{
public:
    virtual void printClass()const = 0;
    virtual ~Base(){}
};

class Derived: public Base
{
private:
    int m_var1;
    std::string m_var2;
public:
    Derived() = default;
    Derived(const int& v1, const std::string& v2)
        :m_var1(v1), m_var2(v2)
        {        }

    void printClass()const override
    {
        std::cout << "Derived Class with\t";
        std::cout << m_var1 << " " << m_var2 << std::endl;
    }
    ~Derived(){ std::cout << "Derived destroyed" << std::endl; }
};

现在在main()中使用多态性我可以声明如下:

int main()
{
    std::shared_ptr<Base> Obj[3];
    Obj[0] = std::make_shared<Derived>(1,"One");
    Obj[1] = std::make_shared<Derived>(2,"Two");
    Obj[2] = std::make_shared<Derived>(3,"Three");

    for(const auto& it: Obj)
        it->printClass();
    return 0;
}

但是,我目前正在尝试详细了解std::shared_ptr<>()及其自定义删除技术,我发现了以下声明。

std::shared_ptr<Base> Obj(new Derived[3], [](Derived* obj){ delete[] obj; });

std::shared_ptr<Base> Obj(new Derived[3] = { 
                                              {1,"One"}, 
                                              {2,"Two"}, 
                                              {3,"Three"} 
                                           }, 
                                           [](Derived* obj){ delete[] obj; });

我的问题是:

  1. 为什么我不能以下列方式初始化或传递值到Derived类的构造函数,即使我有一个服装定义的构造函数可用于derived类?还是我错过了什么?
  2. 如果是这样,那么初始化和访问的正确方法是什么 这样的derived class元素数组?

1 个答案:

答案 0 :(得分:1)

您可以像这样调用构造函数:

std::shared_ptr<Base> Obj{
    new Derived[3]{ {1,"One"}, {2,"Two"}, {3,"Three"} },
    [](Derived* obj){ delete[] obj; }
};