Hi if I am creating something on the stack using new I declare it like:
object *myObject = new object(contr, params);
Is there a way to declare this such as:
object *myObject;
myObject = new object(constr, params);
Is this correct?
Yes, that is correct. But new does not create things on the stack, it creates them on the heap.
To create object on the stack you would do:
object myObject(constr, params);
There is no other way to create an object on the stack and once it is created on the stack you can't "recreate" it with the same name later in the same function.
正如其他人所说, new 将在堆上创建 *myObject 。为了完整起见,我将指出指向对象的指针,称为 myObject(注意没有 *)确实以您声明它的方式驻留在堆栈中。由于堆栈变量在您离开函数时超出范围,因此您必须在返回之前删除对象,或者将指针转移到另一个生命周期更长的变量。在从函数返回之前忽略删除指针位于堆栈变量中的堆对象是一种典型的内存泄漏场景(尽管远非唯一)
Yes that is correct but it won't allocate on the stack. Instead it will allocate on the heap. If you want to allocate on the stack, declare it this way
object myObject(contr,params);
If you want the object to be on the stack, you need to say
object myObject(contr, params);
这段代码:
object *myObject;
myObject = new object(constr, params);
...合法且正确。但是请在分配时将 myObject 初始化为某个值。请记住,“myObject”本身不是“对象”的实例,而是指向“对象”的指针的实例。所以当你像这样声明这个指针时:
object *myObject;
...你让它未初始化。相反,请执行以下操作:
object *myObject = 0;
myObject = new object(constr, params);
...当你删除它时:
delete myObject;
myObject = 0;
人们可能会争论你应该将它设置为 NULL 而不是 0,但就语言而言,两者都很好,这主要是风格问题和你的同事习惯的问题。