C ++中的以下短语是什么意思:zero-,default-和value-initialization? [英] What do the following phrases mean in C++: zero-, default- and value-initialization?

查看:1249
本文介绍了C ++中的以下短语是什么意思:zero-,default-和value-initialization?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++中的以下短语是什么意思:

What do the following phrases mean in C++:


  • 零初始化,

  • zero-initialization,

预设初始化和

值初始化

C ++开发人员应该知道什么?

What should a C++ developer know about them?

推荐答案

价值初始化是C ++ 2003标准的新特性 - 它在原来的1998标准中不存在(我认为这可能是唯一的区别,不仅仅是一个澄清)。请参阅基里尔

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):

  • http://stackoverflow.com/questions/620137/syntax-of-new/620402#620402

答案的要点是:


有时新操作符返回的内存将被初始化,有时它不会取决于您要新建的类型是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中有两种类型的初始化:零和默认值


至少说,这是非常复杂的,当不同的方法踢是微妙的。

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 <stdio.h>
#include <string.h>
#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)];
    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
    printf( "m  is %d\n", pB->m);
    return 0;
}

这篇关于C ++中的以下短语是什么意思:zero-,default-和value-initialization?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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