How can I create a Lazy C++ template class that handles types with no default constructor?

£可爱£侵袭症+ 提交于 2019-12-24 11:58:42

问题


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...


回答1:


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
};


来源:https://stackoverflow.com/questions/17632944/how-can-i-create-a-lazy-c-template-class-that-handles-types-with-no-default-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!