3 ms·
Here's [1] an example from Herb Sutter's blog post [2] about the subject: #include <iostream> using namespace std; void example_1_1_1() { in
by wyldfire 8y ago
Here's [1] an example from Herb Sutter's blog post [2] about the subject:
#include <iostream>
using namespace std;
void example_1_1_1() {
int* p = nullptr; // pset(p) = {null} – records that now p is null
{
int x = 0;
p = &x; // A: set pset(p) = {x} – records that now p points to x
cout << *p; // B: ok – *p is ok because {x} is alive
} // C: x destroyed => replace “x” with “invalid” in all psets
// => set pset(p) = {invalid}
cout << *p; // D: error – because pset(p) contains {invalid}
}
<source>:12:11: warning: dereferencing a dangling pointer [-Wlifetime]
cout << *p; // D: error – because pset(p) contains {invalid}
^
<source>:10:3: note: pointee 'x' left the scope here
} // C: x destroyed => replace “x” with “invalid” in all psets
^
1 warning generated.
[1] https://godbolt.org/z/szJjnH https://godbolt.org/z/szJjnH
[2] https://herbsutter.com/2018/09/20/lifetime-profile-v1-0-posted/ https://herbsutter.com/2018/09/20/lifetime-profile-v1-0-post...