何时使用“新的”和什么时候不到,在C ++? [英] When to use "new" and when not to, in C++?

查看:167
本文介绍了何时使用“新的”和什么时候不到,在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

什么时候在C ++中使用new关键字?



$ b b

我应该在C ++中使用new操作符?我来自C#/ Java背景和实例化对象对我很困惑。

When should I use the "new" operator in C++? I'm coming from C#/Java background and instantiating objects is confusing for me.

如果我创建了一个简单的类Point,当我创建一个点应该:

If I've created a simple class called "Point", when I create a point should I:

Point p1 = Point(0,0);

Point* p1 = new Point(0, 0);

有人可以为我说明何时使用新运算子,何时不使用?

Can someone clarify for me when to use the new operator and when not to?

重复:

http://stackoverflow.com/questions/655065/when-should-i-use-the-new-keyword-in-c

相关:

http://stackoverflow.com/questions/392455/about-constructors -destructors-and-new-delete-operators-in-c-for-custom-objects

http://stackoverflow.com/questions/599308/proper-stack-and-heap-usage-in-c

推荐答案

当您希望对象保留时,应使用 new 存在直到 delete 。如果不使用 new ,那么当对象超出作用域时将被销毁。一些例子是:

You should use new when you wish an object to remain in existence until you delete it. If you do not use new then the object will be destroyed when it goes out of scope. Some examples of this are:

void foo()
{
  Point p = Point(0,0);
} // p is now destroyed.

for (...)
{
  Point p = Point(0,0);
} // p is destroyed after each loop

有些人会说使用 new 决定你的对象是在堆还是栈上,但这只是在函数中声明的变量。

Some people will say that the use of new decides whether your object is on the heap or the stack, but that is only true of variables declared within functions.

在下面的示例中,'p'的位置将是其包含对象Foo分配的位置。我更喜欢称之为就地分配。

In the example below the location of 'p' will be where its containing object, Foo, is allocated. I prefer to call this 'in-place' allocation.

class Foo
{

  Point p;
}; // p will be automatically destroyed when foo is.

使用'new'分配(和释放)对象比如果

Allocating (and freeing) objects with the use of 'new' is far more expensive than if they are allocated in-place so its use should be restricted to where necessary.

第二个通过new分配的例子是数组。您不能*在运行时改变就地或堆栈数组的大小,因此您需要一个不确定大小的数组,必须通过新的数组来分配。

A second example of when to allocate via new is for arrays. You cannot* change the size of an in-place or stack array at run-time so where you need an array of undetermined size it must be allocated via new.

Eg

void foo(int size)
{
   Point* pointArray = new Point[size];
   ...
   delete [] pointArray;
}

(* pre-emptive nitpicking-是的,堆栈分配)。

(*pre-emptive nitpicking - yes, there are extensions that allow variable sized stack allocations).

这篇关于何时使用“新的”和什么时候不到,在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆