以下短语在 C++ 中是什么意思:零初始化、默认初始化和值初始化? [英] What do the following phrases mean in C++: zero-, default- and value-initialization?

查看:47
本文介绍了以下短语在 C++ 中是什么意思:零初始化、默认初始化和值初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下短语在 C++ 中的含义是什么:

What do the following phrases mean in C++:

  • 零初始化,

  • zero-initialization,

默认初始化,以及

值初始化

C++ 开发人员应该了解什么?

What should a C++ developer know about them?

推荐答案

需要意识到的一件事是值初始化"是 C++ 2003 标准的新特性——它在 1998 年的原始标准中不存在(我认为它是可能是唯一不仅仅是澄清的区别).请参阅 KirillV. Lyadvinsky 对直接来自标准的定义的回答.

One thing to realize is that 'value-initialization' is new with the C++ 2003 standard - it doesn't exist in the original 1998 standard (I think it might be the only difference that's more than a clarification). See Kirill V. Lyadvinsky's answer for the definitions straight from the standard.

请参阅有关 operator new 行为的先前答案,了解有关这些类型的初始化的不同行为以及它们何时启动(以及它们何时从 c++98 到 C++03):

See this previous answer about the behavior of operator new for details on the the different behavior of these type of initialization and when they kick in (and when they differ from c++98 to C++03):

答案的要点是:

有时 new 操作符返回的内存会被初始化,有时它不会取决于你新建的类型是 POD,还是包含 POD 成员并使用编译器的类-生成默认构造函数.

Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD, or if it's a class that contains POD members and is using a compiler-generated default constructor.

  • 在 C++1998 中有两种类型的初始化:零和默认
  • 在 C++2003 中,添加了第三种类型的初始化,即值初始化.

至少可以说,它相当复杂,而且不同方法的作用很微妙.

To say they least, it's rather complex and when the different methods kick in are subtle.

需要注意的一件事是 MSVC 遵循 C++98 规则,即使在 VS 2008(VC 9 或 cl.exe 版本 15.x)中也是如此.

One thing to certainly be aware of is that MSVC follows the C++98 rules, even in VS 2008 (VC 9 or cl.exe version 15.x).

以下代码段显示 MSVC 和 Digital Mars 遵循 C++98 规则,而 GCC 3.4.5 和 Comeau 遵循 C++03 规则:

The following snippet shows that MSVC and Digital Mars follow C++98 rules, while GCC 3.4.5 and Comeau follow the C++03 rules:

#include <cstdio>
#include <cstring>
#include <new>

struct A { int m; }; // POD
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m

int main()
{
    char buf[sizeof(B)];
    std::memset( buf, 0x5a, sizeof( buf));

    // use placement new on the memset'ed buffer to make sure 
    //  if we see a zero result it's due to an explicit 
    //  value initialization
    B* pB = new(buf) B();   //C++98 rules - pB->m is uninitialized
                            //C++03 rules - pB->m is set to 0
    std::printf( "m  is %d
", pB->m);
    return 0;
}

这篇关于以下短语在 C++ 中是什么意思:零初始化、默认初始化和值初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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