I have to set this pointer to NULL in the constructor and then lazy load when property is touched.
How can i instantiate this to a new instance of a vector ?
I'm not sure i understand you all the way. Why not simply leave the vector empty, and set a boolean that says whether the property was loaded or not? Alternatively, you can use boost::optional
boost::optional< vector<MyType*> >
Or
boost::optional< vector< shared_ptr<MyType> > >
You can then simply receive the object by dereferencing the optional object, and assign a vector to it like usual.
I would not use a pointer for this. It complicates the matter, and you have to think about what happens when you copy the object containing the property, ...
If you really have to use a pointer, you can do it like this
struct A {
A():prop() { }
~A() { delete prop; }
vector< MyType *>& get() {
if(!prop) prop = new vector< MyType* >();
return prop;
}
private:
// disable copy and assignment.
A(A const&);
A& operator=(A const&);
vector< MyType* > *prop;
};
Or use shared_ptr
, which would be the way to go in my program (but boost::optional would still be first option, after which would be the vector-and-boolean option, after which would be the following)
struct A {
typedef vector< shared_ptr<MyType> > vector_type;
vector_type &get() {
if(!prop) {
prop.reset(new vector_type);
}
return *prop;
}
private:
// disable copy and assignment.
A(A const&);
A& operator=(A const&);
shared_ptr< vector_type > prop;
};
Copy and assignment are disabled, as they would share the prop behind the scene (shallow copy), which should be either clearly documented or disabled by deep copying in these functions.