When to handle memory explicitly?
Hello, I'm new to these fora.
I used to "play around" with C and C++ 10 years ago, and I have been coding different languages a little bit also, like asm (embedded systems), PHP, e.t.c.
Something I've never cared about is memory handling. I've now learned how to use the "new" and "delete" operators, but what I haven't been able to find out is basicly when to use them. To illustrate what I mean, i have two examples (regard the code as pseudo code, I've intentionally simplified it for easier reading);
Code:
Class MyClass
{
Public:
MyClass(void);
Private:
int * MyVariable;
};
MyClass::Myclass(void)
{
MyVariable = new int;
*MyVariable = 0;
}
int main(args..)
{
MyClass MyInstance;
}
Code:
Class MyClass
{
Public:
MyClass(void);
Private:
int MyVariable;
};
MyClass::Myclass(void)
{
MyVariable = 0;
}
int main(args..)
{
MyClass * MyInstance;
MyInstance = new MyClass;
}
A third option would be like the last example, but using only "MyClass MyInstance;" to declare and initialize and instance of MyClass.
Now, when should I use the different ways of implementing the memory handling, and when should I just leave it all to the compiler/linker? Is there any difference in example 1 and 2 in regards of efficiency, since a class might have several member variables, so the "new" operator will have to be called multiple times for each instance of the class, whereas in the second example the "new" operator is only called once for each instance of the class? Is that thinking correct? :)
I am thankful for any input on this topic! :)