Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the lifetime and scope of dynamically allocated memory using new operator inside a class method?

I have a class with a method allocating some memory using new operator, can other members of class can excess that memory? How about outside the class?

like image 837
user2614516 Avatar asked Dec 19 '22 19:12

user2614516


2 Answers

In general, dynamically allocated memory will "live" as long as you don't explicitly deallocate it with delete or delete[].

As far as the scope is concerned: there's no such a thing as a scope for dynamically allocated memory. We usually talk about scope for automatic memory (because automatic memory will be deallocated at the end of the scope). The rules for the scope of the pointer to the dynamically allocated memory, on the other hand, are the same as any other automatic object.

In the C++ Standard (N3797 draft) this is specified at §3.7.4/1:

Objects can be created dynamically during program execution (1.9), using new-expressions (5.3.4), and destroyed using delete-expressions (5.3.5). A C++ implementation provides access to, and management of, dynamic storage via the global allocation functions operator new and operator new[] and the global deallocation functions operator delete and operator delete[].

like image 60
Shoe Avatar answered Feb 16 '23 03:02

Shoe


Untill you destory the object exist it remains in memory, furthermore if you provide a pointer to that object (or more common use get/set functions) it can be accessed from outside the class.

like image 30
invalid_id Avatar answered Feb 16 '23 02:02

invalid_id