Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why first element is destroyed?

I have a piece of code like this:

class Data
{
    public:
        Data(const std::vector<int> &_data)
        {
            my_data = _data;
        }

    private:
        std::vector<int> my_data;
};


int main()
{
    std::vector<std::shared_ptr<Data>> vec = {
        std::shared_ptr<Data>(new Data(std::vector<int>({ 1, 2 ,3 }))),
        std::shared_ptr<Data>(new Data(std::vector<int>({ 3, 4 ,5 })))
    };

    // breakpoint

    return 0;
}

somehow when I pause the program to check values (at breakpoint), the first (vec[0]) element is destroyed while the second one (vec[1]) is fine. What is going on here? Is that a bug in compiler? I am using new Visual Studio 2013.

like image 544
Qwrk Avatar asked Nov 02 '13 23:11

Qwrk


1 Answers

What happens is that a bug in VS2013 causes a double delete on the first item of the initializer_list. Here's the flow:

  1. initializer_list is constructed.
  2. target vector is reserved a size of 1 and first item is copied (via copy constructor).
  3. vector grows slowly to initializer_list size.
  4. initializer_list is destroyed via a vector-destructor (i.e. delete[]). Last element is destroyed first.
  5. First element is destroyed again via scalar-destructor (i.e. delete).

I've seen this on another post and verified the behavior using a debugger. See here

For VS2013, initializer_list is good for basic types only.

like image 76
egur Avatar answered Sep 24 '22 12:09

egur