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 / mms zubeir

The most common design is to delete the object reference in
the destructor of the contained class. This will not be
helpful in cases where an exception is thrown.

There are two objects here viz, the container object and
the embedded object.

If the embedded object construction fails, no problem, it
will not cause any memory leaks since there will be no
memory allocated for it.

If the container object construction fails after
constructing the embedded object, there is a chance of
memory leak. We can use exception handling mechanism to
deallocate the object's space.

1. If the embedded object reference is not inside the try
block, then we can use that reference in the catch block to
delete in case of exceptions.

2. Suppose the embedded object reference/pointer is local
to the try block. This time, the reference to it won't be
available in catch block too. So we will not get a chance
to destroy it even in catch block also. So we need to keep
such kind of references in a global variable and will be
available anywhere in the application. So we can delete the
object reference safely.

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Is there a c++ certification?

825


Explain the virtual inheritance in c++.

837


What is a v-table?

918


Write a program using merge () function to combine the elements of array x[ ] and y[ ] into array z[ ].

851


What are the advantages of c++? Explain

830


What is a singleton class c++?

801


What is c++ and its uses?

928


What is a loop? What are different types of loops in c++?

893


Difference between pointer to constant and constant pointer to a constant. Give example.

898


Why are pointers used?

781


What are c++ tokens?

828


What ANSI C++ function clears the screen a) clrscr() b) clear() c) Its not defined by the ANSI C++ standard

831


What is the difference between ++ count and count ++?

877


Can turbo c++ run c program?

861


What is using namespace std in c++?

847