Skip to content

Instantly share code, notes, and snippets.

@tinyzero4
Created January 25, 2019 15:08
Error: The LazyValue<T> class object must not construct an object of type T when it is created
#include "test_runner.h"
#include <functional>
using namespace std;
template<typename T>
class LazyValue {
public:
explicit LazyValue(std::function<T()> init) {
initializer = move(init);
initialized = false;
}
bool HasValue() const {
return initialized;
}
const T &Get() const {
if (!initialized) {
value = initializer();
initialized = true;
}
return value;
}
private:
mutable T value;
mutable bool initialized;
std::function<T()> initializer;
};
void UseExample() {
const string big_string = "Giant amounts of memory";
LazyValue<string> lazy_string([&big_string] { return big_string; });
ASSERT(!lazy_string.HasValue());
ASSERT_EQUAL(lazy_string.Get(), big_string);
ASSERT_EQUAL(lazy_string.Get(), big_string);
}
void TestInitializerIsntCalled() {
bool called = false;
{
LazyValue<int> lazy_int([&called] {
called = true;
return 0;
});
}
ASSERT(!called);
}
int main() {
TestRunner tr;
RUN_TEST(tr, UseExample);
RUN_TEST(tr, TestInitializerIsntCalled);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment