Home > Back-end >  Want to consult with a guy of the delete the repeated use of the problem
Want to consult with a guy of the delete the repeated use of the problem

Time:10-04

Code is not an error, but the runtime, repeat the delete a pointer p
 buyer * p; 
P=new buyer;//to dynamically allocated memory space p
If (s2=="average user")
{
Buyer buy1 (s1, id, num1, num2);//constructs normal user
P=& amp; Buy1;//the base class pointer to the object
}
Else if (s2=="members")
{
Member m1 (s1, id, num1, num2, scale);//member object
P=& amp; M1;
}
Else if (s2=="VIP")
{
VIP v1 (s1, id, num1, num2, d);//VIP object
P=& amp; V1.
}
The else
{
Cout & lt; <"Level input incorrect" & lt; exit(1);
}

Double p1;
P1=p - & gt; Getpay (b1, b2);//print order
Cout & lt; Cout & lt; <"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" & lt; Cout & lt; <"Order information:" & lt; P - & gt; Disp ();
Cout & lt; <"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" & lt; Cout & lt; The delete p;

CodePudding user response:

The paired no problem, it is ok to write a destructor
P=new buyer
The delete p;
But you let p=& amp; Buy1, changed his point, and point to a temporary variable, leave the scope hand buy1 automatic destructor, namely to space first, has not your initial allocation of buyer, the second you to space has been released, behind again delete p; Will repeat release,

CodePudding user response:

CodePudding user response:

Use new and delete in pairs, since you should not point to a new one to leave the if would release address.

CodePudding user response:

reference ggglivw reply: 3/f
use new and delete in pairs, since you should not point to a new one to leave the if would release address.

If it is not new to the compiler let me you must initialize the run through

CodePudding user response:

reference 1st floor gouyanfen response:
the paired no problem, it is ok to write a destructor
P=new buyer
The delete p;
But you let p=& amp; Buy1, changed his point, and point to a temporary variable, leave the scope hand buy1 automatic destructor, namely to space first, has not your initial allocation of buyer, the second you to space has been released, behind again delete p; Will repeat release,

I see thanks for help

CodePudding user response:

refer to the second floor MianHou response:

Thank you see help drawing style monotonous and easy to understand

CodePudding user response:

VoidandNull
reference 4 floor response:
Quote: refer to the third floor ggglivw response:
use new and delete in pairs, since you should not point to a new one to leave the if would release address.

If it is not new to the compiler let me you must initialize the run nor by


This has nothing to do with the new, it is your own code is not initialized

CodePudding user response:

May not need for new p (don't) new and delete a space,
Buyer * p=null; Seems to be ok
  • Related