Why do I need a generic pointer to be invalidated after a change?

According to Herb Sutter at CppCon 2015 , a shared_ptrshould be canceled after the change,

auto sv = make_shared<vector<int>>(100);
shared_ptr<vector<int>>* sv2 = &sv;
vector<int>* vec = &*sv;
int* ptr = &(*sv)[0];
*ptr = 1 ;

vec->push_back(2);        //A: modification
*ptr = 5;                 //Error: ptr was invalidated by "push_back" on line A

ptr = &(*sv)[0];
(*sv2).reset();            //B: modification
vec->push_back(6);         //Error: vec was invalidated by "reset" on line B

My compiler does not catch any of these errors. In any case, we use smart pointers to prevent memory leaks. What is the reason for suppressing modification shared_ptr? To avoid surprises? If so, can we declare it as const? On the other hand, if many operations on vectorcannot be applied due to share_ptr, is it really inconvenient?


After reading the comments, now I begin to understand what he is doing here. A modification shared_ptrinvalidates other raw pointers pointing to it.

dyp , push_back , ptr. , ptr ? , , , , ?

+3
1

Herb " " CPPCon 2015 ( ).

, , , , , , .

shared_ptr to vector, , , , , , .

, undefined. ( reset shared_ptr, vector), , ( ), Bad Thing.

, , , , , ( Visual Studio 2015), GSL, .

, . Visual Studio , , , Herb Microsoft. ; , Visual Studio - , , , , , Microsoft ++, , , , #, ++ .

0

Source: https://habr.com/ru/post/1627502/


All Articles