What do the following phrases mean in C++: zero-, default- and value-initialization?(以下短语在 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 有区别?李>
答案的重点是:
有时 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 中有 2 种类型的初始化:零和默认
- 在 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++ 中的含义是什么:零初始化、默认初始化和值初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:以下短语在 C++ 中的含义是什么:零初始化、默认初始化和值初始化?


- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01