Created
November 23, 2019 00:13
-
-
Save ms705/85b24c7103d7b3d9d6de160ba2f5955d to your computer and use it in GitHub Desktop.
C++ SoftPtr example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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