在 C++ 中,何时使用“new”,何时不使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/679571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:42:18  来源:igfitidea点击:

When to use "new" and when not to, in C++?

c++new-operator

提问by Andrew Grant

Possible Duplicate:
When should I use the new keyword in C++?

可能的重复:
我什么时候应该在 C++ 中使用 new 关键字?

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

我什么时候应该在 C++ 中使用“new”运算符?我来自 C#/Java 背景,实例化对象对我来说很困惑。

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

如果我创建了一个名为“Point”的简单类,当我创建一个点时,我应该:

Point p1 = Point(0,0);

or

或者

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

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

有人可以为我澄清何时使用新运算符,何时不使用?

Duplicate of:

重复:

When should I use the new keyword in C++?

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

Related:

有关的:

About constructors/destructors and new/delete operators in C++ for custom objects

关于 C++ 中自定义对象的构造函数/析构函数和 new/delete 运算符

Proper stack and heap usage in C++?

在 C++ 中正确使用堆栈和堆?

回答by Andrew Grant

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

new当您希望一个对象一直存在直到您使用delete它时,您应该使用它。如果不使用,new则对象超出范围时将被销毁。这方面的一些例子是:

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

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

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

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

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.

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

class Foo
{

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

Allocating (and freeing) objects with the use of newis 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 newis 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.

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

E.g.

例如

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

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

(*先发制人的挑剔 - 是的,有一些扩展允许可变大小的堆栈分配)。

回答by Eclipse

Take a look at this questionand this questionfor some good answers on C++ object instantiation.

看看这个问题这个问题,以获得关于 C++ 对象实例化的一些好的答案。

This basic idea is that objects instantiated on the heap (using new) need to be cleaned up manually, those instantiated on the stack (without new) are automatically cleaned up when they go out of scope.

这个基本思想是在堆上(使用 new)实例化的对象需要手动清理,那些在堆栈上实例化(没有 new)的对象在超出范围时会自动清理。

void SomeFunc()
{
    Point p1 = Point(0,0);
} // p1 is automatically freed

void SomeFunc2()
{
    Point *p1 = new Point(0,0);
    delete p1; // p1 is leaked unless it gets deleted
}

回答by AAA

You should use new when you want an object to be created on the heap instead of the stack. This allows an object to be accessed from outside the current function or procedure, through the aid of pointers.

当您希望在堆上而不是堆栈上创建对象时,您应该使用 new。这允许通过指针的帮助从当前函数或过程外部访问对象。

It might be of use to you to look up pointers and memory management in C++ since these are things you are unlikely to have come across in other languages.

在 C++ 中查找指针和内存管理可能对您有用,因为这些是您在其他语言中不太可能遇到的东西。

回答by Lomilar

New is always used to allocate dynamic memory, which then has to be freed.

New 总是用于分配动态内存,然后必须释放它。

By doing the first option, that memory will be automagically freed when scope is lost.

通过执行第一个选项,该内存将在范围丢失时自动释放。

Point p1 = Point(0,0); //This is if you want to be safe and don't want to keep the memory outside this function.

Point* p2 = new Point(0, 0); //This must be freed manually. with...
delete p2;