Difference of variable initialization in C++
This question already has an answer here:
"Is there any difference between these 2 ways of storing an integer?"
Yes, there is a significant difference.
int X = 100;
Initializes a variable X
on the stack with the value 100
, while
int *pX = new int(100);
allocates memory for an int
on the heap, kept in pointer pX
, and initializes the value to 100
.
For the latter you should notice, that it's necessary to deallocate that heap memory, when it's no longer needed:
delete pX;
第一个是在栈上创建一个变量,而第二个是在堆上创建一个变量并创建一个指向它的指针。
链接地址: http://www.djcxy.com/p/96536.html上一篇: 什么是安全的? 从函数返回一个结构或指针
下一篇: C ++中变量初始化的区别