Have you considered a wrapper class? You might be able to get away with something like a smart pointer, with only const-returning versions of operator*
and operator->
and maybe operator[]
... You can get scoped_ptr
-like behavior out of it as a bonus.
Let's give this a shot, I'm sure people can point out a few flaws:
template <typename T>
class deferred_create_ptr : boost::noncopyable {
private:
mutable T * m_pThing;
inline void createThingIfNeeded() const { if ( !m_pThing ) m_pThing = new T; }
public:
inline deferred_create_ptr() : m_pThing( NULL ) {}
inline ~deferred_create_ptr() { delete m_pThing; }
inline T * get() const { createThingIfNeeded(); return m_pThing; }
inline T & operator*() const { return *get(); }
inline T * operator->() const { return get(); }
// is this a good idea? unintended conversions?
inline T * operator T *() const { return get(); }
};
Use of type_traits
might make this better...
You'd need different versions for array pointers, and you might have to play around a bit with a creator functor or factory object or something if you wanted to pass in arguments to T
's constructor.
But you could use it like this:
class MyClass {
public:
// don't need a constructor anymore, it comes up NULL automatically
QObject * getExpensiveObject() const { return expensive_object_; }
protected:
deferred_create_ptr<QObject> expensive_object_;
};
Time to go off and compile this and see if I can break it... =)