是否可以确保默认构造函数自动将内置类型初始化为0? [英] Is it guaranteed that defaulted constructor initialize built in types automatically to 0?

查看:319
本文介绍了是否可以确保默认构造函数自动将内置类型初始化为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将默认初始化其成员. 但是对于intfloat类型,默认初始化不同于值初始化

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屋!

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