function
<memory>

std::declare_reachable

void declare_reachable (void* p);
Declare pointer as reachable
Declares the object pointed by the safely-derived pointer p reachable, even if later the compiler cannot trace any pointer to it.

This guarantees that, even in compilers implementing strict pointer safety, a dynamic object pointed by p will remain valid until undeclare_reachable is called with a value equal to p. At that point, a safely-derived pointer of the appropriate type can be obtained by the call to undeclare_reachable.

In garbage-collected implementations, a call to this function prevents the garbage collector from destroying the dynamic object pointed by p even if at some point no pointer or reference can be traced to refer to it.

If this function is called multiple times for the same object p, the object is considered reachable until the same number of calls to undeclare_reachable happen.

Parameters

p
A safely-derived pointer, or a null pointer.
If a null pointer, the call has no effect.

Return value

none

Because memory may be needed to be allocated to track the reachability of p, the function may throw a bad_alloc exception.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// declare_reachable / undeclare_reachable example
#include <iostream>
#include <memory>
#include <cstdint>

int main() {
  int * p = new int (1);    // dynamic object

  std::declare_reachable(p);

  p = (int*)((std::uintptr_t)p ^ UINTPTR_MAX);  // scrambling p

  // dynamic object not reachable by any live safely-derived pointer

  p = std::undeclare_reachable((int*)((std::uintptr_t)p ^ UINTPTR_MAX));
  // p is back again a safely-derived pointer to the dynamic object

  std::cout << "p: " << *p << '\n';
  delete p;

  return 0;
}

Output:
p: 1


See also