Are non-static non-reference data member declarations variables?

后端 未结 2 1676
悲&欢浪女
悲&欢浪女 2020-12-19 21:04

I want to reshoot a question based on the answer and appending discussion of:
Why is a non static data member reference not a variable?:

A non-st

相关标签:
2条回答
  • 2020-12-19 21:39

    The argumentation in the accepted answer seems logical to me but it is, based on my understanding of the variable-definition above, conflicting with the standard.

    There is no conflict with the standard, you've misunderstood the text you quote from §3.6.

    A non-static data member is not an object, so it's not a variable either.

    An object occupies a region of storage for the duration of its lifetime (see [intro.object]). A non-static data member declaration does not begin the lifetime of some thing that occupies a region of storage. So it doesn't create an object.

    When you construct an object of the class' type there will be a sub-object corresponding to the data member, but that subobject is created when the enclosing object is created, and only exists for the object's lifetime. It is not created by the declaration of the data member in the class.

    i.e. a subobject for the data member is created when the class object that contains it is created, not when the data member is declared.

    So if it's not an object, then it's not a variable.

    Question Are non-static non-reference data member declarations variables,

    No.

    0 讨论(0)
  • 2020-12-19 21:55

    No, as Igor Tandetnik pointed out in the comments, non-static data member declarations are never variables, because they are never objects. They are declarations that give the member an object type, but there are no objects until an instance of the class is created.

    Quoting Richard Smith:

    I suppose the problem is in the ambiguity of what a "declaration of a reference" is. I believe the intent here is that a "declaration of a reference" is a declaration that declares a particular name to be of reference type (which a non-static data member declaration of reference type does), not necessarily a declaration that causes the lifetime of a particular reference to begin. Conversely, a "declaration of an object" is intended to be interpreted as a declaration that declares a particular name to name a specific object (which a non-static data member declaration does not).

    That is:

      struct A {
        int &a;
        int b;
      };
    

    'a' is a declaration of a reference, and so we need another condition to restrict it from being a variable. 'b' is /not/ a declaration of an object, so we don't need to say anything further.

    Suggestions on how to reword this to make it clearer would be welcome :)

    This was followed up as https://github.com/cplusplus/draft/issues/1280, some inconsistencies were found. With some luck, this will be seen as a good opportunity to clear up the standard at the same time.

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