默认初始化不会对非类类型成员进行零初始化

默认初始化不会对非类类型成员进行零初始化

本文介绍了为什么 C++ 默认初始化不会对非类类型成员进行零初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么标准决定在 默认初始化 但在 零初始化en.cppreference.com/w/cpp/language/value_initialization" rel="nofollow">值初始化?

why the standard decides to do nothing for non-class type members during a default initialization but performs zero initialization during value initialization?

如果总是对非 clss 类型的成员执行零初始化会更安全吗?

Would it be safer if zero initialization is always performed on non-clss type memebers?

推荐答案

语言设计的基本原则之一是你不应该为你不需要的东西买单.如果你想初始化你的成员,你可以要求编译器这样做,但如果你不想这样做,成本不会强加给你.

One of the basic principles of design in the language is that you should not pay for something you don't need. If you want your members initialized, you can ask the compiler to do so, but if you don't want that, the cost won't be forced onto you.

默认初始化只会初始化那些需要初始化的东西,即具有非平凡默认构造函数的成员,因为该构造函数旨在设置一些对物体.请注意,区别不是类类型与基本类型,而是是否存在平凡的构造函数:

Default initialization will only initialize those things that need to be initialized, that is, the members that have a non-trivial default constructor, as that constructor is meant to set some invariants that are important for the object. Note that the distinction is not class-type vs. fundamental type, but rather whether there is a trivial constructor or not:

struct POD { int a; int b; int c; };
struct V { virtual void f(); };
struct Type {
   std::string str;       // default initialization calls default constructor
   V           obj;       //  " calls default constructor: vptr must be set
   POD         pod;       // default initialization leaves this untouched
};

这篇关于为什么 C++ 默认初始化不会对非类类型成员进行零初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 10:04