C ++ atminties valdymas: naujas ir ištrintas

Šioje pamokoje išmoksime efektyviai valdyti atmintį naudodami C ++, naudodami naujas ir ištrinamas operacijas, naudodamiesi pavyzdžiais.

C ++ leidžia mums paskirstyti kintamojo ar masyvo atmintį vykdymo metu. Tai vadinama dinaminiu atminties paskirstymu.

Kitomis programavimo kalbomis, tokiomis kaip „Java“ ir „Python“, kompiliatorius automatiškai valdo kintamiesiems skirtas atmintis. Tačiau C ++ atveju taip nėra.

C ++ sistemoje dinamiškai paskirstytą atmintį turime paskirstyti rankiniu būdu, kai kintamasis nenaudojamas.

Mes galime dinamiškai paskirstyti ir paskui paskirstyti atmintį naudodami atitinkamai newir deleteoperatorius.

C ++ naujas operatorius

newOperatorius paskirsto atmintį kintamąjį. Pavyzdžiui,

 // declare an int pointer int* pointVar; // dynamically allocate memory // using the new keyword pointVar = new int; // assign value to allocated memory *pointVar = 45;

Čia dinamiškai paskirstėme atmintį intkintamajam naudodami newoperatorių.

Atkreipkite dėmesį, kad mes naudojome žymeklį pointVar dinamiškai paskirstyti atmintį. Taip yra todėl, kad newoperatorius grąžina atminties vietos adresą.

Masyvo atveju newoperatorius grąžina pirmojo masyvo elemento adresą.

Iš aukščiau pateikto pavyzdžio galime pamatyti, kad newoperatoriaus naudojimo sintaksė yra

 pointerVariable = new dataType;

ištrinti operatorių

Kai nebereikia naudoti dinamiškai deklaruoto kintamojo, galime paskirstyti kintamojo užimtą atmintį.

Tam deletenaudojamas operatorius. Jis grąžina atmintį į operacinę sistemą. Tai vadinama atminties paskirstymu .

Šio operatoriaus sintaksė yra

 delete pointerVariable;

Apsvarstykite kodą:

 // declare an int pointer int* pointVar; // dynamically allocate memory // for an int variable pointVar = new int; // assign value to the variable memory *pointVar = 45; // print the value stored in memory cout << *pointVar; // Output: 45 // deallocate the memory delete pointVar;

Čia dinamiškai priskyrėme intkintamojo atmintį naudodami žymeklį pointVar.

Atspausdinę „pointVar“ turinį, mes paskirstėme atmintį naudodami delete.

Pastaba : Jei programa naudoja daug nepageidaujamos atminties new, sistema gali sugesti, nes operacinei sistemai nebus laisvos atminties. Tokiu atveju deleteoperatorius gali padėti sistemai sugesti.

1 pavyzdys: C ++ dinaminės atminties paskirstymas

 #include using namespace std; int main() ( // declare an int pointer int* pointInt; // declare a float pointer float* pointFloat; // dynamically allocate memory pointInt = new int; pointFloat = new float; // assigning value to the memory *pointInt = 45; *pointFloat = 45.45f; cout << *pointInt << endl; cout << *pointFloat << endl; // deallocate the memory delete pointInt, pointFloat; return 0; )

Rezultatas

 45 45.45

Šioje programoje mes dinamiškai priskyrėme atmintį dviem kintamiesiems intir floattipams. Priskyrę joms vertes ir jas atsispausdinę, pagaliau paskirstome atmintines naudodami kodą

 delete pointInt, pointFloat;

Pastaba: Dinaminis atminties paskirstymas gali padaryti atminties valdymą efektyvesnį.

Ypač masyvams, kur daug kartų mes nežinome masyvo dydžio iki paleidimo laiko.

2 pavyzdys: C ++ new ir ištrinkite masyvų operatorių

 // C++ Program to store GPA of n number of students and display it // where n is the number of students entered by the user #include #include using namespace std; int main() ( int num; cout <> num; float* ptr; // memory allocation of num number of floats ptr = new float(num); cout << "Enter GPA of students." << endl; for (int i = 0; i < num; ++i) ( cout << "Student" << i + 1 <> *(ptr + i); ) cout << "Displaying GPA of students." << endl; for (int i = 0; i < num; ++i) ( cout << "Student" << i + 1 << " :" << *(ptr + i) << endl; ) // ptr memory is released delete () ptr; return 0; )

Rezultatas

Įveskite bendrą studentų skaičių: 4 Įveskite studentų GPA. Studentas1: 3,6 Studentas2: 3,1 Studentas3: 3,9 Studentas4: 2,9 Rodoma studentų GPA. Studentas1: 3,6 Studentas2: 3,1 Studentas3: 3,9 Studentas4: 2,9

Šioje programoje mes paprašėme vartotojo įvesti mokinių skaičių ir išsaugoti jį kintamajame num.

Tada dinamiškai paskirstėme atmintį floatmasyvui, naudodami naują.

Duomenis į masyvą įvedame (o vėliau atspausdiname) naudodami žymeklio žymėjimą.

Po to, kai masyvo mums nebereikia, mes paskirstome masyvo atmintį naudodami kodą delete () ptr;.

Atkreipkite dėmesį į ()po delete. Mes naudojame laužtinius skliaustus (), norėdami pažymėti, kad atminties paskirstymas yra masyvas.

3 pavyzdys: C ++ new ir ištrinkite objektų operatorių

 #include using namespace std; class Student ( int age; public: // constructor initializes age to 12 Student() : age(12) () void getAge() ( cout << "Age = " << age 

Output

 Age = 12

In this program, we have created a Student class that has a private variable age.

We have initialized age to 12 in the default constructor Student() and print its value with the function getAge().

In main(), we have created a Student object using the new operator and use the pointer ptr to point to its address.

The moment the object is created, the Student() constructor initializes age to 12.

We then call the getAge() function using the code:

 ptr->getAge();

Notice the arrow operator ->. This operator is used to access class members using pointers.

Įdomios straipsniai...