Skip to content

Instantly share code, notes, and snippets.

@ms705
Created November 23, 2019 00:13
Show Gist options
  • Save ms705/85b24c7103d7b3d9d6de160ba2f5955d to your computer and use it in GitHub Desktop.
Save ms705/85b24c7103d7b3d9d6de160ba2f5955d to your computer and use it in GitHub Desktop.
C++ SoftPtr example
#include <functional>
#include <stdio.h>
template <class T> class SoftPtr {
public:
SoftPtr(T *inner) { this->inner = inner; }
SoftPtr<T> operator*() { return SoftPtr(this->inner); }
void use(std::function<void(T &)> code) {
// disable preemption, make rcu_reader, etc.
code(*inner);
}
private:
T *inner;
};
class Foo {
public:
Foo() {}
int say() { return 42; }
};
int main() {
Foo f;
SoftPtr<Foo> x(&f);
// doesn't compile:
// Foo &a = *x;
SoftPtr<Foo> y = *x;
y.use([](Foo &a) -> void { a.say(); });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment