lo tolmencre
lo tolmencre

Reputation: 3934

Does Pointer to Dynamic Container Persist?

I know dynamic data structures like vectors, lists, maps and sets allocate their elements on the heap autonomously, therefore I cannot take a pointer to an element and expect it to stay valid, if the data structure gets modified. But can I make a pointer to the structure itself and know that it will always stay valid? I would assume the structure has some kind of anchor in the stack, that will always have the same address or something, regardless of where its elements are allocated... ?

so, can I safely do something like this with STL dynamic containers?

int main()
{

    std::set<int> s;
    std::set<int>* s_ptr = &s;

    for (int i = 0; i < 1000000; ++i)
    {
        s.insert(i);
    }

    std::cout << s_ptr->size() << std::endl;

}

In my test this did work. But because of UB I cannot rely on that.

Upvotes: 0

Views: 46

Answers (1)

R Sahu
R Sahu

Reputation: 206567

Your usage of the pointer is safe. The pointer will be valid as long as s is alive. In this case, s will be alive until the end of the function.

Upvotes: 3

Related Questions