Hello, please can I have some clarification to check I am not doing something very stupid? It seems sensible with all that I have read, but I'm not confident. I suspect I have memory leaks and want to make sure some fundamentals are correct before I start looking deeper.
My code is very big so I can't reproduce it here. Instead, I have tried to illustrate with a simpler example.
In my code I have a class:
class MyClass {
...
int Member;
public:
setMember(int value);
...
}
MyClass::setMember(int value)
{
Member=value;
}
Originally, when I passed my instance of the class, I would pass it as a pointer:
char * myFunction(int testValue, MyClass *thisMyClass )
{
...
thisMyClass->setMember(testValue);
...
}
void main(){
int aValue;
MyClass * thisMyClass;
aValue=20;
thisMyClass = new MyClass;
myFunction(aValue, thisMyClass);
delete thisMyClass;
}
However in this case, I believe that, thisMyClass
was actually out of scope within myFunction()
. I believe this because the memory occupied by thisMyClass
kept getting overwritten.
Therefore, I started passing by reference:
char * myFunction(int testValue, MyClass &thisMyClass )
{
...
thisMyClass.setMember(testValue);
...
}
void main(){
int aValue;
MyClass thisMyClass;
aValue=20;
myFunction(aValue, thisMyClass);
}
Questions:
- Was I right in believe that
thisMyClass
was out of scope in myFunction()? - Am I right in passing by reference in this case where I am expecting
thisMyClass
to be changed bymyFunction()
? - Should I be using
delete
anywhere in the second example (I don't think I should as I have not instantiated withnew
)?