1
可能重复:
When should I use the new keyword in C++?管理对象变量生存期的最佳方法是什么?
我不是一个专业的程序员,我只有经验与小项目的工作,所以我有一个小麻烦了解什么是怎么回事。
我通常使用class_name var_name
创建对象。但是现在我正在'学习'Objective-C,几乎所有的东西都是一个指针,并且你对内存使用有更多的控制。
现在我创建一个包含无限循环的应用程序。
我的问题是,哪个选项是一个更好的方式来管理内存使用(导致更少的内存使用)?
一个正常的声明(对我来说)
#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; }
使用
new
和delete
#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; }
我认为选择2使用更少的内存,更有效地释放了双端队列。那是对的吗?他们之间有什么[其他]差异?
我真的很困惑在哪里使用每个选项。
现在持有。这两个版本并没有做同样的事情。那么,真正的问题是什么? – 2011-12-17 11:47:46
感谢您的语法编辑。我疯狂地把它放在正确的方式。 – 2011-12-17 11:48:51
Nitpick on your English:“伙计”一词并不意味着问题,它通常意味着一个朋友。 :-) – 2011-12-17 11:52:26