vendredi 23 mars 2018

custom deleter for a unique_ptr that owns an array of base pointers

class A{
    string m_name;
    int m_num;
public:
    A(string name="", int number=1) : m_name(name), m_num(number){
        cout << "ctorA " << m_name << endl;
    }

    virtual ~A(){ cout << "dtorA " << m_name << endl; }     
    virtual string getName()                { return m_name; }
    virtual void setName(const string name) { m_name = name; }
    virtual int getNumber()                 { return m_num; }
};

class B : public A{
    string m_name;
    int m_num;
public:
    B(string name="B", int num=2) : A("A", 1), m_name(name), m_num(num){
        cout << "ctorB " << m_name << endl;
    }

    ~B(){ cout << "dtorB " << m_name << endl; }             

    string getName() override                   { return m_name; }
    void setName(const string name) override    { m_name = name; }
    int getNumber() override                    { return m_num; }
};  

    auto deleter = [](A* ptr){delete ptr;};
    unique_ptr< A[], decltype(deleter) > upABArr(new A[3], deleter);

    upABArr[0] = new B("B1");  //trying to store pointer in array not value
    upABArr[1] = new B("B2");
    upABArr[2] = new B("B3");

    for(int i=0; i<3; i++){
        cout << "Name: " << upABArr[i]->getName() << endl;
    }

Trying to set up a custom deleter for a unique_ptr that owns an array of A pointers. A is base class.

Not sure what I'm doing wrong but I think there are multiple errors. Template argument is wrong according to compiler. No match for = operator, etc.

Aucun commentaire:

Enregistrer un commentaire