ehds
ehds

Reputation: 785

Why shared ptr in vector not delete with reserve

class A{
    public:
        A(){cout<<"constructor"<<endl;}
        ~A(){cout<<"destructor"<<endl;}
};

int main()
{   
    {
        //case 1
        vector<std::shared_ptr<A>> vec;
        vec.reserve(1);
        vec[0] = std::make_shared<A>();
    }
    // Not destructor
    {
        //case 2
        vector<std::shared_ptr<A>> vec;
        vec.emplace_back(std::make_shared<A>());
    }
    // Called destructor
  return 0;
}

Why vec at end of life, the element within it not be deleted in case1.result

If we not reserve vector, but emplace back element to vec, it works.

Upvotes: 0

Views: 155

Answers (1)

Lukas-T
Lukas-T

Reputation: 11340

TL;DR: I guess this is a typo and you meant to call resize(1) instead of reserve(1), but I'd like to explain a bit, because I see how one could easily confuse the two functions.


std::vector has a capactiy (the total slots that can be used) and a size (the number of slots actually used).

reserve() will increase the capacity, i.e. make room for more elements, but it will not increase the size. That's the job of resize():

vec.reserve(1); // capacity >= 1, size = 0!

Access to a vector is out of bounds if the index is >= the vector's size, irrespective of it's capacity, thus

vec[0] = std::make_shared<A>();

is out of bounds and leads to undefined behaviour. (index 0 >= size 0)

Upvotes: 4

Related Questions