While refactoring some code for performance the other day, I needed an answer to creating member variables that are lazy initialized, but that also provides a convenient, though optional, non-lambda interface for non c++11 compilers.
Here's the typical pattern for lazy instantiation that I want to abstract:
if( !bInitialized )
{
value = doInitialization();
bInitialized = true;
}
return value;
For my use, I'd like some flexibility:
- allow explicit initialization, like the example above
- provide implicit access to the lazy as if it were the underlying datatype
- handle uninitialized access (throws), in case I screw up on explicit initialization (e.g., forget to assign a value)
- also support real lazy initialization via a function, functor and/or lambda
- allow manual initialization via pointer to the contained value (e.g., when calling Win32 API's)
- allow reassignment of the value; treat the lazy as the underlying datatype in most cases.
I have code that I'm going to post as an answer, but would be interested in different approaches. Your answer need not satisfy all these requirements; simpler may be better for some use cases...
Here's my solution, including a unit test suite built on the Microsoft Native Unit Test Library.
It handles the requirements of the OP - a single Lazy class that provides:
Plus,
First, an example of usage:
And, here is the code. This version uses the stdc++11 library, but can easily be converted to use boost.
Lazy.hpp
test_Lazy.cpp