Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic Array as a class member problem 1

Status
Not open for further replies.

nawaf

Programmer
Jun 11, 2001
12
0
0
KW
Hello,
I've been coding a class for which there is a dynamic array member, in the constructor I wrote :

...
Blah = new Whatever[numberOfElements];
...


in the destructor of course I have to delete this array, or there will be a memory leake, so, I wrote in the destructor:

....
delete [] Blah ;
....


every thing works fine, until I call a static member function, for which the parametters are of this class, after the call of the function, the array blah does not exist where I called the member function, the code looks like this:


....

MyClass x1;
MyClass::StaticFunction(x1);
....


after the static function returns, the member array Blah is deleted, here what happens, when I call the fumction, the parametter is copied and passed to the function yClass::StaticFunction(x1), a typical pass by value, at the end of this function, the copy of object x1 is deleted, with all of its members, the Blah array Blah member is dhared with x1 in the caller function, so it is deleted as well, I want to prevent this from hapenning, yet, I don't want leaks to happen, can nayone help Please? I would be greatly appreciated.
 
Personal ideea.

Try to put another function between your class and the static function like this:

MyClass x1;
MyClass::StaticFunction(x1.GiveMeTheClass());

and

MyClass MyClass::GiveMeTheClass()
{
return *this;
}

hope this will help you or give you some other ideeas, s-)

Blessed is he who in the name of justice and good will, shepards the week through the valley of darknees...
 
The problem is what when you put x1 as a parameter it is created and deleted from the stack. When it is created it uses now a default constructor but when delete it uses the destructor. For avoid it make a copy constructor:
MyClass(MyClass& x)
{
copy there the array from x
} John Fill
1c.bmp


ivfmd@mail.md
 
By the way, this is the problem not only for static functions. Try to see every types if funtions.
An other method to avoid this conflict is to not allow a copy to delete array from the destructor:

MyClass
{
int is_copy;
OneArrayHere
public:

MyClass:is_copy(0)()
MyClass:is_copy(1)(MyClass& x)
{
}
~MyClass()
{
if(is_copy)return;
delete theArray;
}
};
first method
MyClass
{
OneArrayHere
public:

MyClass(){alloc the array}
MyClass(MyClass& x)
{
alloc and copy the array from x
}
~MyClass()
{
delete theArray;
}
};
John Fill
1c.bmp


ivfmd@mail.md
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top