Possible Duplicate:
When should I use the new keyword in C++?
I'm not a professional programmer and I only have experience working with small projects, so I'm having a little trouble understanding what's going on here.
I usually create objects using class_name var_name
. But now I'm 'learning' Objective-C, where almost everything is a pointer and you have more control over memory usage.
Now I'm creating an application which contains an infinite loop.
My question is, which option is a better way to manage memory usage (resulting in less memory usage)?
A normal declaration (for me)
#include <stdio.h> #include <iostream> #include <deque> using namespace std; class myclass { public: int a; float b; deque<int> array; myclass() {cout <<"myclass constructed\n";} ~myclass() {cout <<"myclass destroyed\n";} //Other methods int suma(); int resta(); }; int main(int argc, char** argv) { myclass hola; for(1) { // Work with object hola. hola.a = 1; } return 0; }
Using
new
anddelete
#include <stdio.h> #include <iostream> #include <deque> using namespace std; class myclass { public: int a; float b; deque<int> array; myclass() {cout <<"myclass constructed\n";} ~myclass() {cout <<"myclass destroyed\n";} //Other methods int suma(); int resta(); }; int main(int argc, char** argv) { myclass hola; for(1) { myclass *hola; hola = new myclass; // Work with object hola. hola->a = 1; delete hola; } return 0; }
I think option 2 uses less memory and frees the deque more efficiently. Is that correct? What are the [other] differences between them?
I'm really confused about where to use each option.