mardi 24 octobre 2017

Scoped variable storage duration

consider this code:

#include <iostream>
#include <vector>

class T
{
public:
    T(int c=1): c(c), ptr(new int(c))
    {}    
    T(const T& other)
    {
        c = other.c;
        ptr = new int(*other.ptr);
    }    
    ~T()
    {
        delete ptr;
    }    
    int c;
    int* ptr;
};    

int main()
{
    std::vector<T> a = { 1, 2, 3, 4, 5 };
    a.clear();    
    for (int i = 0; i < 5; i++) {
        std::cout << a[i].c << ' ';
    }
    return 0;
}

After calling clear() as we would normally expect it to not print anything in the console, however for some reason it still outputs 1 2 3 4 5 on g++ (tried on 5.4) ... but throws vector subscript out of range exception on MSVS 2015.

I know that clear can have (and most probably) have different implementations on different platforms

So is it left to the particular compiler implementation to decide the lifetime of c ?

What standard can say here ?

Why they are kept after clearing vector ?

Aucun commentaire:

Enregistrer un commentaire