CPP with pointer, how to put temporary variables of classes with destructors into vector?

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

  1. * 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
  2. .
  3. also because the cost of p calculation is too high, I don"t want to recalculate it again after calculating it
  4. 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
  5. .

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?

CPP
Oct.10,2021
Why does the

variable a have to be placed inside the for loop?
because the actual scope of the p pointer of an is not limited to the for loop at all, it is completely meaningless to declare the variable an in the for loop.
of course, if you think you must insist on declaring the variable an inside the for loop, you can do this:
remove the release delete operation from the destructor of class A, write a class A member function specifically for delete p, and then manually call A's delete member function after vector.


using shared_ptr, multiple copies of the same an are all the same p, and temporary an is the same p as push_back to vector, but you need to pay attention to the state in p. After all, multiple copies of an are all reading and writing the same p

.
A{
public:
T * p = NULL;
A(){}
T* getP () {if(p == NULL)p=new T(); return p;}
~A() (if(p!=NULL){delete p;p=NULL;})
A(A&& other)
{
  std::swap(p, other.p);
}
operator= (A&& other)
{
  std::swap(p, other.p);
}
}


for(){
A a();
if(validate(a))vector.insert(std::move(a));
}
Menu