简体   繁体   English

std :: cout是否初始化(或预初始化)指针?

[英]Does std::cout initialize (or pre-initialize) a pointer?

I have a question about pointers in C++. 我对C ++中的指针有疑问。

I know you can't delete a uninitialized pointer and if you want to use delete , the pointer should be initialized first. 我知道您不能删除未初始化的指针,并且如果要使用delete ,则应该首先初始化该指针。 But does std::cout somehow "initialize" it? 但是std :: cout是否以某种方式“初始化”了它?
If I try to run the code below it will crash during the execution. 如果我尝试运行下面的代码,它将在执行期间崩溃。

#include <iostream>
int main (){
   int *ptr;
   delete ptr;
   return 0;
}

This is what I'd expect and I'm fine with it because the pointer is not initialized. 这是我所期望的,我也满意,因为未初始化指针。 However if I try to run the code below it won't crash! 但是,如果我尝试运行下面的代码,它将不会崩溃!

#include <iostream>
int main (){
   int *ptr;
   std::cout << ptr << std::endl; //This is the new line
   delete ptr;
   return 0;
}

I know that the pointer ptr is not initialized because I can't assign anything to it, if I add this line before the delete 我知道指针ptr尚未初始化,因为如果我在删除之前添加此行,则无法为其分配任何内容

*ptr = 5;

The program will crash as expected. 该程序将按预期崩溃。 Why, then the program won't crash if I use the std::cout before delete? 为什么,如果在删除前使用std :: cout ,程序将不会崩溃? I know cout didn't initialize the pointer, but is this somehow a "pre-initialization"(or something else)? 我知道cout并未初始化指针,但这是以某种方式“预初始化”(或其他方式)吗?
Thanks! 谢谢!
Ezra 以斯拉

Deleting an uninitialized pointer is undefined behavior. 删除未初始化的指针是未定义的行为。

Undefined behavior may crash your program, if you are lucky. 如果您很幸运,未定义的行为可能会使您的程序崩溃。 You were unlucky, and your program did not crash. 您很不幸,您的程序没有崩溃。

In this case, when you call delete ptr , the compiler knows that the ptr is garbage. 在这种情况下,当您调用delete ptr ,编译器会知道ptr是垃圾。 Perhaps it just calls delete with whatever value is handy, and if you use cout , nullptr just coincidentally happens to be that value. 也许它只是用任何方便的值调用delete ,如果您使用cout ,那么巧合的是nullptr就是那个值。

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

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