在 C 中新建/删除 C++ 的等价物是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2839551/
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-28 11:13:39  来源:igfitidea点击:

What's the equivalent of new/delete of C++ in C?

c++cnew-operatordelete-operator

提问by httpinterpret

What's the equivalent of new/delete of C++ in C?

在 C 中新建/删除 C++ 的等价物是什么?

Or it's the same in C/C++?

还是在 C/C++ 中是一样的?

回答by kennytm

There's no new/deleteexpression in C.

C 中没有new/delete表达式。

The closest equivalent are the mallocand freefunctions, if you ignore the constructors/destructors and type safety.

如果忽略构造函数/析构函数和类型安全,则最接近的等效项是mallocfree函数

#include <stdlib.h>

int* p = malloc(sizeof(*p));   // int* p = new int;
...
free(p);                       // delete p;

int* a = malloc(12*sizeof(*a));  // int* a = new int[12];
...
free(a);                         // delete[] a;

回答by fredoverflow

Note that constructors might throw exceptions in C++. The equivalent of player* p = new player();would be something like this in C.

请注意,构造函数可能会在 C++ 中引发异常。player* p = new player();在 C 中相当于是这样的。

struct player *p = malloc(sizeof *p);
if (!p) handle_out_of_memory();
int err = construct_player(p);
if (err)
{
    free(p);
    handle_constructor_error();
}

The equivalent of delete pis simpler, because destructors should never "throw".

相当于delete p更简单,因为析构函数永远不应该“抛出”。

destruct(p);
free(p);

回答by Pete Kirkham

Use of newand deletein C++ combines two responsibility - allocating/releasing dynamic memory, and initialising/releasing an object.

在 C++ 中使用newdelete结合了两个职责 - 分配/释放动态内存和初始化/释放对象。

As all the other answers say, the most common way to allocate and release dynamic memory is calling mallocand free. You also can use OS-specific functions to get a large chunk of memory and allocate your objects in that, but that is rarer - only if you have fairly specific requirements that malloc does not satisfy.

正如所有其他答案所说,分配和释放动态内存的最常见方法是调用mallocfree。您还可以使用特定于操作系统的函数来获取大量内存并在其中分配您的对象,但这种情况很少见 - 仅当您有 malloc 不满足的相当特定的要求时。

In C, most APIs will provide a pair of functions which fulfil the other roles of newand delete.

在C中,大多数API将提供对那些履行的其他角色的功能newdelete

For example, the file api uses a pair of open and close functions:

例如,文件 api 使用一对打开和关闭函数:

// C++
fstream* fp = new fstream("c:\test.txt", "r");
delete fp;

// C
FILE *fp=fopen("c:\test.txt", "r"); 
fclose(fp);

It may be that fopenuses mallocto allocate the storage for the FILEstruct, or it may statically allocate a table for the maximum number of file pointers on process start. The point is, the API doesn't require the client to use mallocand free.

这可能是因为fopen使用malloc分配的存储的FILE结构体,或者它可以静态分配的表为文件指针的工艺开始时的最大数目。关键是,API 不需要客户端使用mallocfree

Other APIs provide functions which just perform the initialisation and releasing part of the contract - equivalent to the constructor and destructor, which allows the client code to use either automatic , static or dynamic storage. One example is the pthreads API:

其他 API 提供的函数只执行合约的初始化和释放部分——相当于构造函数和析构函数,它允许客户端代码使用自动、静态或动态存储。一个例子是 pthreads API:

pthread_t thread;

pthread_create( &thread, NULL, thread_function, (void*) param); 

This allows the client more flexibility, but increases the coupling between the library and the client - the client needs to know the size of the pthread_ttype, whereas if the library handles both allocation and initialisation the client does not need to know the size of the type, so the implementation can vary without changing the client at all. Neither introduces as much coupling between the client and the implementation as C++ does. (It's often better to think of C++ as a template metaprogramming language with vtables than an OO language)

这使客户端具有更大的灵活性,但增加了库和客户端之间的耦合 - 客户端需要知道pthread_t类型的大小,而如果库同时处理分配和初始化,则客户端不需要知道类型的大小,因此实现可以在不改变客户端的情况下发生变化。两者都没有像 C++ 那样引入客户端和实现之间的耦合。(将 C++ 视为带有 vtables 的模板元编程语言通常比 OO 语言更好)

回答by Gaurav Vaish

Not directly an exact replica but compatible equivalents are malloc and free.

不是直接的精确副本,但兼容的等价物是 malloc 和 free。

<data-type>* variable = (<data-type> *) malloc(memory-size);
free(variable);

No constructors/destructors - C anyway doesn't have them :)

没有构造函数/析构函数 - C 反正没有它们:)

To get the memory-size, you can use sizeofoperator.

要获得内存大小,您可以使用sizeof运算符。

If you want to work with multidimensional arrays, you will need to use it multiple times (like new):

如果要使用多维数组,则需要多次使用它(如 new):

int** ptr_to_ptr = (int **) malloc(12 * sizeof(int *)); //assuming an array with length 12.
ptr[0] = (int *) malloc(10 * sizeof(int));   //1st element is an array of 10 items
ptr[1] = (int *) malloc(5 * sizeof(int));    //2nd element an array of 5 elements etc

回答by Ashish Jindal

Use malloc / free functions.

使用 malloc/free 函数。

回答by ishidex2

Late, but I really like this syntax, although I'm not sure if it fits ways of C

晚了,但我真的很喜欢这种语法,虽然我不确定它是否适合 C 的方式

#include <stdlib.h>

#define new(type, length) malloc(sizeof(type)*(length))
#define delete(x) free(x)
int main()
{
    int *test = new(int, 30);
    delete(test);
}