Writing a Default Constructor Forces Zero-Initialization?

前端 未结 3 475
有刺的猬
有刺的猬 2021-01-06 23:23

These are my class definitions:

class Foo{
    int _ent;
public:
    void printEnt() const{cout << _ent << \' \';}
};

class Bar{
    Foo _foo;
p         


        
相关标签:
3条回答
  • 2021-01-06 23:52

    When you provided a default constructor you no longer get the compiler generated one. Since your default constructor initializes the member to 0 the member will always be 0, this is especially true since the member is private and you have no way to change it.

    0 讨论(0)
  • 2021-01-06 23:54

    Your question has been answered in the C++11 revision of the standard:

    class Foo{
        int _ent=0;
    public:
    
        // ...
    };
    

    If you then define your own default constructor, the member will still be initialized to its default value, even if your default constructor does not explicitly do so.

    0 讨论(0)
  • 2021-01-06 23:55

    Once you provide a constructor for a type, it will always be invoked, both for default initialization and for value initialization. It's a fundamental principle of the language. So once you define Foo::Foo(), it will be called any time you construct a Foo; if there is a default constructor, it will be invoked, even in the case of default initialization. So the behavior you are seeing is correct.

    EDIT:

    Default initialization is explained §8.5/7, in particular:

    To default-initialize an object of type T means:

    — if T is a (possibly cv-qualified) class type (Clause 9), the default constructor (12.1) for T is called [...]

    In your case, you'll probably also want to look at how the compiler generates a default constructor if none is provided, §12.1/4; in particular, the generated default constructor invokes the default constructor of any base classes or members.

    Value initialization is in §8.5/8. It is basically default initialization preceded by zero initialization, so that default initialization that doesn't do anything still finds everything zero initialized.

    More fundamentally, however: in this case, a very fundamental principle of C++ is involved, dating to long before the first standard: if you provide a constructor for an object, it will be used. Without doing all sorts of strange pointer casts, it is impossible to get an object without it being properly constructed. The standard describes how this occurs, and covers a lot of other special cases, but the basic principle has been there from the start (and any proposal which would cause it not to be respected in the standard is bound to fail).

    0 讨论(0)
提交回复
热议问题