Last active
June 26, 2018 23:28
-
-
Save bdon/23a05c633259f6781f10f4739f183e41 to your computer and use it in GitHub Desktop.
lazy
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
# 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()) |
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
// 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