dimanche 2 mai 2021

Destructor and erase for shared pointers

As far as I know destructor is called when an element is erased from container, please correct me if I'm wrong..But Destr X prints shouldn't appear before after erase

#include <iostream>
#include <memory>
#include <vector>

struct X 
{
    X()
    {
        std::cout<<"Contr X"<<std::endl;
    }
    ~X()
    {
        std::cout<<"Destr X"<<std::endl;
    }
};

using Xptr = std::shared_ptr<X>;

int main()
{
    
    std::shared_ptr<X> x = std::make_shared<X>();
    Xptr x2 = std::make_shared<X>();
    std::vector<Xptr> v;
    v.emplace_back(x);
    v.emplace_back(x2);
    v.erase(v.begin());
    std::cout<<"after erase\n";
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire