Does copying an empty object involve accessing it

后端 未结 2 1815
悲哀的现实
悲哀的现实 2021-02-07 11:05

Inspired from this question.

struct E {};
E e;
E f(e);  // Accesses e?

To access is to

read or modify the value of an object<

2条回答
  •  温柔的废话
    2021-02-07 11:51

    I think it does not access the object, though a valid object is required to be present.

    E f(e);
    

    This calls E's implicitly defined constructor E::E(const E&). Obviously the body of this constructor is empty (because there is nothing to do). So if anything happens, it must happen during argument passing, i.e. during the initialization of const E& from e.

    It is self-evident that this initialization does not modify e. Now, to read the value of e, a lvalue-to-rvalue conversion must take place. However, the standard actually says that this conversion does not take place during direct reference binding1. That is to say, no read is performed.

    However, the standard does require that a reference must be initialized to refer to a valid object or function2 (though this is subject to CWG 453), so things like E f(*reinterpret_cast(nullptr)); will be ill-formed.


    1. This is done by not normatively requiring such conversion, and further strengthened by the non-normative note in [dcl.init.ref].

    2. [dcl.ref].

提交回复
热议问题