Click here to Skip to main content
15,910,980 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi smart ones,
I have a question regarding a class inside itself. Here is a dummy code:

C++
//.h
class MyClass{
public:
 MyClass();
 virtual ~MyClass();
 
 MyClass* prev;
 void Set_Prev(MyClass& cap);
};

//.cpp
void MyClass::Set_Prev(MyClass& cap){
   prev = new MyClass();
   *prev = cap;
}


Now everything is OK here, but I'm left with a memory leak. How to overcome this, as I can't call delete right away, the prev is used in other parts in the code. And calling delete in MyClass's deconstructor is giving me errors on runtime. Any input will be appreciated :)

[edit] addition by the OP in a non-solution moved here[/edit]
How to be sure that it is a deep copy? I initialise with new first, as otherwise I get error in the operator= I have added to the class.
Posted
Updated 1-May-12 8:26am
v2

See comments inside code below


C++
//.h
class MyClass{
public:
 MyClass();
 virtual ~MyClass();
 
 MyClass* prev;
 void Set_Prev(MyClass& cap);
};
 
//.cpp
void MyClass::Set_Prev(MyClass& cap){
   prev = new MyClass();    
//Why are you doiing this. here you are allocating memory for it and then not using it at all  and in next line you have attached the pointer to something else coming from outside. so there are as many objects leaked as many times you call this fucntion. remove this line.
   *prev = cap;
}


[edit] sorry, i think i misinterpreted last time the right way to do this would be

C++
//.cpp
void MyClass::Set_Prev(MyClass& cap){
if(prev != 0)
{
   delete prev;
   prev = 0;
}
   prev = new MyClass();

   *prev = cap;   //just make sure you have proper copy constructor doing deep copy not shallow one.
}
 
Share this answer
 
v3
Why do you new up prev if you're just going to overwrite it with cap?

Remove the prev = new MyClass();.

Hope this helps,
Fredrik
 
Share this answer
 
If a reference is fine, try:

C++
void MyClass::Set_Prev(MyClass& cap){
   prev = ∩
}


That sets the prev pointer to point to cap.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900