本文介绍了何时在C ++中使用新的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是一个好的政策,什么时候使用新来创建类的实例?我一直爱好编程C ++一段时间,但我仍然不确定什么时候是最好的时间做这个:
What's a good policy for when to use "new" to make an instance of a class? I've been hobby programming C++ for a while but I'm still not for sure when is the best time to do this:
MyClass thing(param1, param2);
:
MyClass* thing;
thing = new MyClass(param1, param2);
任何建议?
推荐答案
MyClass thing(param1, param2); //memory for thing is allocated on the process stack(static allocation)
MyClass* thing;
thing = new MyClass(param1, param2); //memory is allocated dynamically on the heap(free store) for thing
这里的区别在于: / p>
The difference lies here:
int main()
{
{
MyClass thing(param1, param2); //thing is local to the scope
} //destructor called for thing
//cannot access thing (thing doesn't exist)
}
int main()
{
{
MyClass* thing;
thing = new MyClass(param1, param2);
}
//the object pointed to by thing still exists
//Memory leak
}
对于大型对象,您必须动态分配内存(使用new),因为进程堆栈的大小有限。
For large objects you must allocate memory dynamically(use new) because the process stack has a limited size.
这篇关于何时在C ++中使用新的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!