在c ++中的空构造函数 [英] Empty constructor in c++

查看:940
本文介绍了在c ++中的空构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解的部分,我会得到一些随机值,但是在代码片段中的 Foo()构造函数像默认public构造函数,编译器当我们没有定义构造函数时提供?

Well I understand the part that I will be getting some random value, but is theFoo() constructor in the snippet acting just like the default public constructor which the compiler supplies when we have no constructor defined?

#include<iostream>
using namespace std ;

class Foo{
        int i  ;
    public:
        Foo(){
        }
        void disp(){
            cout<<"i = "<<i  ;
        }
};

int main(){
    Foo bar1,bar2 ;
    bar1.disp();
    cout<<"\n";
    bar2.disp();
}



我看到一些人写这样的空构造函数,

I have seen some people writing an empty constructor like this, but I could't understand exactly why/when is it to be used?

推荐答案

没有参数的用户定义的ctor,没有ctor-init-列表和空主体的行为与默认的ctor几乎相同。

有一个区别,它不算作一个简单的ctor,

A user-defined ctor without arguments, without ctor-init-list and with an empty body behaves nearly the same as the default-ctor.
There is one difference though, it does not count as a trivial ctor, ever!

这样的默认默认值会避免这种差异和伴随的潜在性能下降:

Explicitly defaulting like this instead would avoid that difference and the concomittant potential performance-degradation:

Foo() = default; // Needs C++11

什么是default一个类函数声明之后是什么意思?

参见< type_traits> 以检测差异: http://en.cppreference.com/w/cpp/types/ is_constructible

这篇关于在c ++中的空构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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