1

Deleting this question in favor the following; an answer to which now handles classes with no default constructor:

How to abstract lazy initialization in C++?

In a nutshell, the code uses placement new/delete. See http://en.wikipedia.org/wiki/Placement_syntax for details...

Community
  • 1
  • 1
James Hugard
  • 3,232
  • 1
  • 25
  • 36

1 Answers1

3

Just use boost::optional<T> instead of pair of your members m_bInitialized and m_value. Probably you could just use boost::optional<T> instead of your template class Lazy...

If you really want to make it in your own way - then steal some implementation details from boost::optional<T>.

One hint is that this boost class uses placement new:

class Lazy {
public:
   bool is_init() const { return m_memberPtr != nullptr; }
   T& force() 
   { 
      if (!is_init()) 
        m_memberPtr = new (m_memberMemory) T(m_initializer());
      return *m_memberPtr;
   }
private:
  T* m_memberPtr;
  alignas(T) char m_memberMemory[sizeof(T)]; // s
};
Community
  • 1
  • 1
PiotrNycz
  • 23,099
  • 7
  • 66
  • 112
  • Rather than use boost::optional, I think using a shared_ptr in the target datatype will give what I want with minimal fuss. – James Hugard Jul 14 '13 at 15:47
  • I get it now, but boost::optional only satisfies explicit lazy instantiation via assignment; it doesn't handle implicit lazy instantiation via callback and explicit instantiation via passing as a pointer to a getter function, such as with many Win32 API's. I am/was looking for a single class to do all 3. – James Hugard Jul 14 '13 at 18:41
  • @JamesHugard See my update. As I said, you can steal some implementation details from `boost::optional` - like this placement new trick. In this way you have memory in your class for the object, you can pass it to some "C" API to initialize it in other way. – PiotrNycz Jul 14 '13 at 19:24
  • as I said, I'm going to delete this question and ask in a simpler, more direct fashion. Also, I created a new question to discuss lazy initialization in C++, here: http://stackoverflow.com/questions/17642824/how-do-i-do-lazy-initialization-or-lazy-instantiation-in-c/17642967#17642967 – James Hugard Jul 14 '13 at 19:37