What is definition of reference type?

前端 未结 4 2292
攒了一身酷
攒了一身酷 2020-12-30 17:12

How do you define (explain) in a formal and strict way what is reference type in C++?

I tried to google, and looked into Stroustrup\'s \"The C++ Programming Language

4条回答
  •  梦毁少年i
    2020-12-30 17:57

    According to some experts' views reference types are not C++ references per se, but in contrast to value types. I present two slightly differing definitions - of value types and of reference types.

    https://abseil.io/blog/20180531-regular-types

    The first is a blog post by Titus Winters, chair of the C++ subcommittee responsible for the C++ standards library.

    According to Titus Winters, the difference between a value type and a reference type is the copy behaviour. When you copy value type, you get two independent objects, which are equal first, but may differ after the modification of one of both. When you copy a reference type, you get two objects, which refer to the same data.

    Reference types do not own their data. Some reference types allow modifying the referred-to data (e.g. span), some do not (e.g. string_view). Both examples given are quite useful for function parameter passing. The caller of the function assures that the underlying data of the reference types is not destructed during the duration of the function call (as is the case with plain C++ references).

    https://docs.microsoft.com/en-us/cpp/cpp/value-types-modern-cpp?view=vs-2019

    The Microsoft documentation puts reference types as synonymous to polymorphic types (types with at least one virtual function or member variable), and value types as non-polymorphic. (Non-polymorphic types are called concrete types by Bjarne Stroustrup.)

    Value types are about memory and layout control, reference types are about identity.

    Value types allow the compiler direct access to the members, reference types need an indirection due to runtime polymorphism.

    Reference types according to Microsoft are non-copyable (to prevent slicing).

    So the semantics differ, as Titus Winters defines reference types by their actual copy behaviour.

提交回复
热议问题