我正在学习 C++,我知道“new”关键字用于将内存中的地址分配给指针。我认为当使用“nullptr”时会初始化一个指向任何内容的指针。那是对的吗?参考示例:
//using nullptr
int *x = nullptr; //this is just a pointer that points to nothing and
//will need to be initialized with an address before it
//it can be used. Correct?
//using new
int *x = new int; //this is basically giving x an address in memory. Will the
//address have some residual value stored in it or will
//it contain zero?
Run Code Online (Sandbox Code Playgroud)
你什么时候会使用其中一种而不是另一种?new 仅用于动态内存分配还是还有其他应用?如果你可以先声明一个指向 nullptr 的指针,然后再初始化它,为什么还要初始化它呢?
谢谢您的帮助!