-
Notifications
You must be signed in to change notification settings - Fork 0
New and delete
MarJC5 edited this page Oct 28, 2022
·
1 revision
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by a programmer. Dynamically allocated memory is allocated on Heap, and non-static and local variables get memory allocated on Stack.
The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is available, a new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.
Since it is the programmer’s responsibility to deallocate dynamically allocated memory, programmers are provided delete operator in C++ language.
Syntax to use new && delete operator
class Student {
private:
std::string _login;
public:
Student() : _login("default") {
std::cout << "Student " << this->_login << " is born" << std::endl;
}
~Student() {
std::cout << "Student " << this->_login << " died" << std::endl;
}
};
int main(void) {
// Then request memory for the variable
Student* = new student("jmartin");
// deallocate dynamically allocated
delete student;
}