在C ++中初始化数组 [英] Initialising arrays in C++

查看:231
本文介绍了在C ++中初始化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无处不在,我看到有人争辩说,未初始化的变量是坏的,我当然同意和理解为什么 - 然而;我的问题是,有时候你不想这样做吗?

Everywhere I look there are people who argue vociferously that uninitialised variables are bad and I certainly agree and understand why - however; my question is, are there occasions when you would not want to do this?

例如,取代码:

char arrBuffer[1024] = { '\0' };

在不初始化数组的情况下,

Does NULLing the entire array create a performance impact over using the array without initialising it?

推荐答案

我假设一个堆栈初始化,因为静态数组是自动初始化的。

G ++ output

I assume a stack initialization because static arrays are auto-initialized.
G++ output

   char whatever[2567] = {'\0'};
   8048530:       8d 95 f5 f5 ff ff       lea    -0xa0b(%ebp),%edx
   8048536:       b8 07 0a 00 00          mov    $0xa07,%eax
   804853b:       89 44 24 08             mov    %eax,0x8(%esp)
   804853f:       c7 44 24 04 00 00 00    movl   $0x0,0x4(%esp)
   8048546:       00 
   8048547:       89 14 24                mov    %edx,(%esp)
   804854a:       e8 b9 fe ff ff          call   8048408 <memset@plt>

所以,你用{'\0'}初始化并调用memset是的,你有一个性能打击。

So, you initialize with {'\0'} and a call to memset is done, so yes, you have a performance hit.

这篇关于在C ++中初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆