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 is #include iostream h in c++?
How would you find out if a linked-list is a cycle or not?
How to demonstrate the use of a variable?
Distinguish between new and malloc and delete and free().
What is an incomplete type in c++?
List the advantages of inheritance.
What are the uses of c++ in the real world?
What are the advantages of using a pointer? Define the operators that can be used with a pointer.
Is c++ platform dependent?
Explain the pure virtual functions?
What is c++ best used for?
write asingle linked list which read from two list & the do the following 1 sort the prime & nonprime num (prime should be less tn nonprime) 2 each node has a prime num followd by nonprime 3 add a new node into its sutable plce 4 erase the most three duplicated non prime num 5 find the least duplicated prime num
What is a v-table?
the maximum length of a character constant can be a) 2 b) 1 c) 8
Is c++ built on c?