problem description
the environment is scientific computing software, and speed is very critical.
for example, there is a class
A {
public:
T* paired null;
A () {}
T* getP () {if (p = = NULL) p=new T (); return p;}
~ A () (if (paired null) {delete pumped null;})
}
now you need
for () {
An a ();
if (validate (a)) vector.insert (a);
}
at this point, because the scope of the variable an is only inside the for loop, the destructor is called when you jump out of the current loop step. If the user chooses a function related to p, the valuable p will be deleted, but the copy of an inside vector is unaware that it has been deleted, thus causing bug.
because
- * p is a member that takes up a lot of space, is slow to calculate, and is probably not needed by the user, so it uses pointers to save .
- also because the cost of p calculation is too high, I don"t want to recalculate it again after calculating it
- for the same reason, I don"t want to implement rule of 3, I don"t want to traverse p, or I want to deep copy * p .
desired answer
at present, I use the method of saving A temporary variables outside scope to enhance the life cycle of temporary variables, such as
vector tmp;
for () {
tmp.insert (A ());
A & a = tmp [I];
if (validate (a)) vector.insert (a);
}
because the business logic related to * p is finished here,
but I wonder if there is a more standard and elegant method?