是否可以确保默认构造函数自动将内置类型初始化为0? [英] Is it guaranteed that defaulted constructor initialize built in types automatically to 0?
问题描述
在开始将其标记为重复之前,我已经阅读了这个 .但是它不能回答我的问题.链接的问题涉及C ++ 98& C ++ 03,但我的问题是关于C ++ 11引入的默认构造函数.
Before you start to mark this as duplicate I've already read this .But It doesn't answer my question. The linked question talks about C++98 & C++03 but my question is about defaulted constructor introduced by C++11.
考虑以下程序(请参见在线演示此处):
Consider following program (See live demo here):
#include <iostream>
struct Test
{
int s;
float m;
Test(int a,float b) : s(a),m(b)
{ }
Test()=default;
}t;
int main()
{
std::cout<<t.s<<'\n';
std::cout<<t.m<<'\n';
}
我的问题是,编译器提供的默认构造函数始终在C ++ 11&中默认将内置类型初始化为默认值0.当它们是class
& ;;时为C ++ 14. struct
个成员. C ++ 11标准可以保证这种行为吗?
My question is that is the defaulted constructor provided by compiler here always initializes built in types to by default 0 in C++11 & C++14 when they are class
& struct
members. Is this behavior guaranteed by C++11 standard?
推荐答案
Test = default
将默认初始化其成员.
但是对于int
或float
类型,默认初始化不同于值初始化
Test = default
will default initialize its members.
but for type as int
or float
, default initialization is different than value-initialization
如此
Test t; // t.s and t.m have unitialized value
而
Test t{}; // t.s == 0 and t.m == 0.0f;
这篇关于是否可以确保默认构造函数自动将内置类型初始化为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!