In a class, there is a reference or pointer of an object of
another class embedded, and the memory is either allocated
or assigned to the new object created for this class. In
the constructor, parameters are passed to initialize the
data members and the embedded object reference to get
inialized. What measures or design change should be advised
for proper destruction and avioding memory leaks, getting
pointers dangling for the embedded object memory
allocation? Please suggest.
Answer Posted / ravindranath m
Embedded object is of reference type. That is, its possible
that the constructor of the container class would receive an
argument that is a reference to the embedded class object.
So, there should be a copy-constructor and/or
copy-assignment operator implemented for the embedded
object's class.
As stated in the problem statement, the embedded object ptr
is "either allocated memory" or "assigned memory".
Since the embedded object is a *reference* to an object, its
quite possible that actual object of embedded type is
constructed elsewhere and passed as an arg to the container
class. This also means that someone outside the container
class is also having a reference to the embedded class. It
implies that this embedded object can be deleted outside the
class, in which case the embedded object ptr may become a
dangling ptr.
The best approach seems to be the implementation of smart
pointer aka shared pointer, which can do reference counting
and destroy itself only when no more references are present.
see www.boost.org (or google search) for information on
shared pointers.
Is This Answer Correct ? | 2 Yes | 0 No |
Post New Answer View All Answers
What do you mean by friend class & friend function in c++?
What is flag in computer?
Which recursive sorting technique always makes recursive calls to sort subarrays that are about half size of the original array?
Is sorted c++?
Is main a class in c++?
How to declare an array of pointers to integer?
Write a c program for binary addition of two 8 bit numbers.
Differentiate between a template class and class template in c++?
Reads in the size of a square from the screen; 2. Prints a hollow square of that size out of “-“, “|” and blanks on screen; 3. Prints the same hollow square onto a text file. Your program should work for squares of all side sizes between 1 and 20. --- │ │ │ │ │ │ ---
What is static class data?
List different attributes in C++?
What is near, far and huge pointers? How many bytes are occupied by them?
What are the effects after calling the delete this operator ?
How much do coding jobs pay?
What is the use of map in c++?