简体   繁体   English

C++ 动态内存分配使用“new”

[英]c++ dynamic memory allocation using "new"

I'm new to C++, trying to learn by myself (I've got Java background).我是 C++ 新手,正在尝试自学(我有 Java 背景)。

There's this concept of dynamic memory allocation that I can assign to an array (for example) using new .我可以使用new将动态内存分配的概念分配给数组(例如)。

In C (and also in C++) I've got malloc and realloc that are doing that.在 C(以及 C++)中,我有mallocrealloc正在这样做。 In C++ they've added the new for some reason I can't understand.在 C++ 中,由于某种我无法理解的原因,他们添加了new的。

I've read a lot about the difference between a normal array that goes to the stack while the dynamic allocated array goes to the heap.我已经阅读了很多关于进入堆栈的普通数组与进入堆的动态分配数组之间的区别的文章。

So what I understand is that by using new I'm allocating space in the heap which will not be deleted automatically when finished a function let's say, but will remain where it is until I finally, manually free it.所以我的理解是,通过使用new我在堆中分配空间,当完成一个函数时不会自动删除,但会保持原位,直到我最终手动释放它。

I couldn't find practical examples of using the dynamic memory allocation over the normal memory.我找不到在普通内存上使用动态内存分配的实际示例。

  1. It's said that I can't allocate memory through runtime when using normal array.据说使用普通数组时无法通过运行时分配内存。 Well, probably I didn't understand it right because when I tried to create a normal array (without new ) with a capacity given as an input by the user (like arr[input] ), it worked fine.好吧,可能我没有正确理解它,因为当我尝试创建一个普通数组(没有new )时,它的容量由用户作为输入给出(如arr[input] ),它工作正常。

here is what I mean:这就是我的意思:

int whatever;
cin>>whatever;

int arr2[whatever];

for (int i = 0; i < whatever; i++) {
    arr2[i]=whatever;
    cout<<arr2[i];

}
  1. I didn't really understand why it's called dynamic when the only way of extending the capacity of an array is to copy it to a new , larger array.当扩展数组容量的唯一方法是将它复制到一个new更大的数组时,我真的不明白为什么它被称为动态。

I understood that the Vector class (which I haven't yet learned) is much better to use.我知道 Vector 类(我还没有学过)更好用。 But still, I can't just leave that gap of knowledge begin and I must understand why exactly it's called dynamic and why should I use it instead of a normal array.但是,我仍然不能离开知识的空白开始,我必须明白为什么它被称为动态,为什么我应该使用它而不是普通数组。 Why should I bother freeing memory manually when I can't really extend it but only copy it to a new array?当我无法真正扩展内存而只能将其复制到新数组时,为什么还要手动释放内存?

When you know the size of an array at compile time you can declare it like this and it will live on the stack:当您在编译时知道数组的大小时,您可以像这样声明它,并且它将存在于堆栈中:

int arr[42];

But if you don't know the size at compile time, only at runtime, then you cannot say:但是如果你在编译时不知道大小,只在运行时知道,那么你不能说:

int len = get_len();
int arr[len];

In this case you must allocate the array at runtime.在这种情况下,您必须在运行时分配数组。 In this case the array will live on the heap.在这种情况下,数组将存在于堆中。

int len = get_len();
int* arr = new int[len];

When you no longer need that memory you need to do a delete [] arr .当您不再需要该内存时,您需要执行delete [] arr

std::vector is a variable size container that allows you to allocate and reallocate memory at runtime without having to worry about explicitly allocating and freeing it. std::vector是一个可变大小的容器,它允许您在运行时分配和重新分配内存,而不必担心显式分配和释放它。

int len = get_len();
std::vector<int> v(len); // v has len elements
v.resize(len + 10); // add 10 more elements to the vector

For static allocation, you must specify the size as a constant:对于静态分配,您必须将大小指定为常量:

  MyObj  arrObject[5];

For dynamic allocation, that can be varied at run-time:对于动态分配,可以在运行时改变:

  MyObj  *arrObject = new MyObj[n];

The different between new and malloc is that new will call the ctor for all those objects in the array, while malloc just gives you raw memory. newmalloc的不同之处在于new会为数组中的所有对象调用构造malloc ,而malloc只给你原始内存。

if you wanna use an array and you dont know the exact size at the compile time, thats when dynamic memory allocation steps in. See the example below,如果你想使用一个数组并且你在编译时不知道确切的大小,那就是动态内存分配介入的时候。见下面的例子,

int a[3] = {1,2,3};  //<= valid in terms of syntax;

however,然而,

int size = 3;
int a[size] = {1,2,3} //<= compile error

in order to fix this,为了解决这个问题,

int* ArrayPtr = new int[size];

also, when freeing it, call delete[] ArrayPtr;另外,在释放它时,调用delete[] ArrayPtr; instead of delete alone, coz we are talking abt freeing a BLOCK of memory at this moment.而不是单独delete ,因为我们现在谈论的是释放一块内存。

In C (and also in C++) I've got malloc and realloc that are doing that.在 C(以及 C++)中,我有 malloc 和 realloc 正在这样做。 In C++ they've added the "new" for some reason I can't understand.在 C++ 中,出于某种我无法理解的原因,他们添加了“新”。

malloc and realloc take the number of bytes to allocate instead of the type you want to allocate, and also don't call any constructors (again, they only know about the size to allocate). malloc 和 realloc 使用要分配的字节数而不是您要分配的类型,并且也不调用任何构造函数(同样,它们只知道要分配的大小)。 This works fine in C (as it really has more of a size system than a type system), but with C++'s much more involved type system, it falls short.这在 C 中运行良好(因为它确实有更多的大小系统而不是类型系统),但是对于 C++ 涉及更多的类型系统,它有不足之处。 In contrast, new is type safe (it doesn't return a void* as malloc does) and constructs the object allocated for you before returning.相比之下, new 是类型安全的(它不像 malloc 那样返回 void* )并在返回之前构造为您分配的对象。

It's said that I can't allocate memory through runtime when using normal array.据说使用普通数组时无法通过运行时分配内存。 Well, probably I didn't understand it right because when I tried to create a normal array (without "new") with a capacity given as an input by the user (like arr[input]).好吧,可能我没有理解正确,因为当我尝试创建一个普通数组(没有“new”)时,其容量由用户作为输入(如 arr[input])给出。 it worked fine.它工作正常。

This is a compiler extension (and part of C99), it is NOT standard C++.这是一个编译器扩展(也是 C99 的一部分),它不是标准的 C++。 The standard requires that a 'normal' array have a bound which is known at compile time.该标准要求“正常”数组具有在编译时已知的边界。 However, it seems your compiler decided to support variable length 'normal' arrays anyways.但是,您的编译器似乎决定无论如何都支持可变长度的“普通”数组。

I didn't really understand why it's called dynamic when the only way of extending the capacity of an array is to copy it to a new, larger array.当扩展数组容量的唯一方法是将它复制到一个新的更大的数组时,我真的不明白为什么它被称为动态。

Its dynamic in that you don't know the size until run time (and thus can be different across different invocations).它的动态性在于您直到运行时才知道大小(因此在不同的调用中可能会有所不同)。 Compile time vs. run time is a distinction you don't often run across in other languages (in my experience at least), but it is crucial to understanding C++.编译时间与运行时间是您在其他语言中不常遇到的区别(至少以我的经验),但它对于理解 C++ 至关重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM