为什么默认情况下不使用 NULL 初始化指针?

2021-12-13 00:00:00 initialization memory pointers c++

有人可以解释为什么指针没有初始化为 NULL 吗?
示例:

Can someone please explain why pointers aren't initialized to NULL?
Example:

  void test(){
     char *buf;
     if (!buf)
        // whatever
  }

程序不会进入 if 因为buf 不为空.

The program wouldn't step inside the if because buf is not null.

我想知道为什么,在什么情况下我们需要一个带垃圾的变量,特别是指向内存垃圾的指针?

I would like to know why, in what case do we need a variable with trash on, specially pointers addressing the trash on the memory?

推荐答案

我们都意识到应该初始化指针(和其他 POD 类型).
那么问题就变成了谁应该初始化它们".

We all realize that pointer (and other POD types) should be initialized.
The question then becomes 'who should initialize them'.

基本上有两种方法:

  • 编译器初始化它们.
  • 开发人员初始化它们.

让我们假设编译器初始化了任何未由开发人员显式初始化的变量.然后我们遇到了初始化变量不是微不足道的情况,开发人员没有在声明点这样做的原因是他/她需要执行一些操作然后赋值.

Let us assume that the compiler initialized any variable not explicitly initialized by the developer. Then we run into situations where initializing the variable was non trivial and the reason the developer did not do it at the declaration point was he/she needed to perform some operation and then assign.

所以现在我们的情况是,编译器在代码中添加了一条额外的指令,将变量初始化为 NULL,然后添加开发人员代码以进行正确的初始化.或者在其他条件下,变量可能永远不会被使用.许多 C++ 开发人员会以额外的指令为代价在这两种情况下尖叫.

So now we have the situation that the compiler has added an extra instruction to the code that initializes the variable to NULL then later the developer code is added to do the correct initialization. Or under other conditions the variable is potentially never used. A lot of C++ developers would scream foul under both conditions at the cost of that extra instruction.

这不仅仅是时间问题.但也有空间.在很多环境中,这两种资源都非常宝贵,开发人员也不想放弃.

It's not just about time. But also space. There are a lot of environments where both resources are at a premium and the developers do not want to give up either.

BUT:可以模拟强制初始化的效果.大多数编译器会警告您未初始化的变量.所以我总是把我的警告级别调到可能的最高级别.然后告诉编译器将所有警告视为错误.在这些情况下,大多数编译器都会为未初始化但已使用的变量生成错误,从而阻止生成代码.

BUT: You can simulate the effect of forcing initialization. Most compilers will warn you about uninitialized variables. So I always turn my warning level to the highest level possible. Then tell the compiler to treat all warnings as errors. Under these conditions most compilers will then generate an error for variables that are un-initialized but used and thus will prevent code from being generated.

相关文章