As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center作为指导。
6年前关闭。
我什么时候应该使用
在我的示例中,使用两种不同的方法可以获得相同的结果:
6年前关闭。
我什么时候应该使用
new-operator
?在我的示例中,使用两种不同的方法可以获得相同的结果:
#include <iostream>
int main() {
int *p1;
int n1 = 5;
p1 = &n1;
int *p2;
p2 = new int;
*p2 = 5;
std::cout << *p1 << std::endl;
std::cout << *p2 << std::endl;
return 0;
}
最佳答案
使用动态分配的内存的目的是以下一种(或多种)
对对象生命周期的运行时控制。例如。该对象由new
手动创建,并由delete
手动销毁。
对对象类型的运行时控制。例如。您可以在运行时忽略多态对象的实际类型。
对对象数量的运行时控制。例如。您可以在运行时确定数组大小或列表中元素的数量。
当对象太大而无法合理放置到任何其他类型的内存中时。例如。很大的输入输出缓冲区,太大而无法在堆栈上分配
在您的特定示例中,所有这些原因均不适用,这意味着在那里使用动态内存根本没有意义。
关于c++ - 什么时候使用new-operator? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16825229/