What is an int() Called?

后端 未结 3 860
闹比i
闹比i 2020-12-10 12:14

It\'s been rehashed over and over that primitive types don\'t have constructors. For example this _bar is not initialized to 0 when I call Foo():

3条回答
  •  被撕碎了的回忆
    2020-12-10 12:45

    It's been rehashed over and over that primitive types don't have constructors.

    That's right.

    For example this bar is not initialized to 0 when I call Foo()

    Yes it is. Foo() specifies value-initialisation which, for class like this with no user-provided constructor, means it's zero-initialised before initialising its members. So _bar ends up with the value zero. (Although, as noted in the comments, one popular compiler doesn't correctly value-initialise such classes.)

    It would not be initialised if you were to use default-initialisation instead. You can't do that with a temporary; but a declared variable Foo f; or an object by new F will be default-initialised. Default-initialisation of primitive types does nothing, leaving them with an indeterminate value.

    It would also not be initialised if the class had a user-provided default constructor, and that constructor didn't specifically initialise _bar. Again, it would be default-initialised, with no effect.

    So obviously int() is not a constructor. But what is it's name?

    As an expression, it's a value-initialised temporary of type int.

    Syntactically, it's a special case of an "explicit type conversion (functional notation)"; but it would be rather confusing to use that term for anything other than a type conversion.

    In this example I would say i is: (constructed? initialized? fooed?)

    Initialised. List-initialised (with an empty list), value-initialised, or zero-initialised, if you want to be more specific.

提交回复
热议问题