lundi 15 février 2021

Smart pointers to an object explicitly created object

I have read a lot of issues created in regard to this but was not able to answer my question.

I have created a class as follows -

class exampleClass{
public: 
    exampleClass(int n){
        cout<<"Created Class"<<endl;
        this->number = n;
    }

    ~exampleClass(){
        cout<<endl<<"This class is destroyed Now"<<endl;
    }

    template<typename t> t 
    addNum(t a, t b){
        return a + b;
    }

    void print(){
        cout<<this->number<<endl;
    }
private:
    int number;
};

and I make 2 shared_ptr(or for that matter unique_ptr, error is same) as follows -

int main(){
   exampleClass* object = new exampleClass(60);

   std::shared_ptr<exampleClass> p1(object);
   std::shared_ptr<exampleClass> p2 (object);
   p1->print();
}

Now the error it throws at the end is -

free(): double free detected in tcache 2
Aborted (core dumped)

I am not able to understand why the error at the end. Shouldn't the above code be equal to p2 =p1(in case of shared_ptr) or p2 = std::move(p1) for unique_ptr as both the pointers are for the same object?

TIA
PS - The title might be a little misleading or not accurate,but I did not know what exactly should be a title.

Aucun commentaire:

Enregistrer un commentaire