简体   繁体   English

为什么使用“new”运算符?

[英]Why use the "new" operator?

The code below is an example that was used to demonstrate some logic in C++下面的代码是一个示例,用于演示 C++ 中的一些逻辑

int *p = new int;
*p = 5;

cout << *p << endl;

delete p;

In this particular example, there is no reason for dynamic allocation (which is what new provides).在这个特定的例子中,没有理由进行动态分配(这是new提供的)。

It looks like a toy example to show how you would dynamically allocate, set, print, then delete an int .它看起来像一个玩具例子来告诉你如何动态分配,集打印,然后删除int

In reality, you wouldn't do this unless you had a more complex type to create, or you really needed the int to be shared between scopes for some reason (though, even then, smart pointers are nowadays preferred).实际上,除非您要创建更复杂的类型,否则您不会这样做,或者您出于某种原因确实需要在作用域之间共享int (尽管如此,现在还是首选智能指针)。

Refer to your book for more information on dynamic allocation and when it is (and isn't) useful.有关动态分配的更多信息以及它何时(以及何时)有用,请参阅您的书。

Why did we use "new" operator here and what is the role of "new" operator in C++?为什么我们在这里使用“ new”运算符? “ new”运算符在C ++中的作用是什么?

int *p = new int; //Here in this line
*p = 5;

cout << *p << endl;

delete p;

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

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