Skip to content

Instantly share code, notes, and snippets.

@bdon
Last active June 26, 2018 23:28
Show Gist options
  • Save bdon/23a05c633259f6781f10f4739f183e41 to your computer and use it in GitHub Desktop.
Save bdon/23a05c633259f6781f10f4739f183e41 to your computer and use it in GitHub Desktop.
lazy
# example of how to make a method invocation
# "lazy" by not doing the work until first access
class A:
def __init__(self):
self.mValue = None
def getValue(self):
if not self.mValue:
print("doing something expensive")
self.mValue = "value"
return self.mValue
a = A()
print(a.getValue())
print(a.getValue())
// attempt to port to c++17
#include <iostream>
#include <experimental/optional>
using namespace std;
using namespace std::experimental;
class A {
public:
const string &getValue() const {
if (!mValue) {
cout << "doing something expensive" << endl;
mValue.emplace("value");
}
return *mValue;
}
private:
mutable optional<const string> mValue;
};
int main() {
// A is logically const but not physically const.
const A a;
cout << a.getValue() << endl;
cout << a.getValue() << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment