why copy constructor is called when passing temporary by const reference?

前端 未结 3 1771
后悔当初
后悔当初 2020-12-05 14:24

I am passing an unnamed temporary object to a function defined with const ref parameter. The copy ctor of the class is private, and I get a compilation error. I don\'t under

3条回答
  •  醉话见心
    2020-12-05 14:51

    The expression A(1) is an rvalue 5.2.3 [expr.type.conv].

    In initializing a const reference (the function argument) with an expression that is an rvalue the compiler may create a temporary and copy the value of that expression to the temporary and bind that reference to that temporary. 8.5.3 [dcl.init.ref] / 5.

    [...] The constructor that would be used to make the copy shall be callable whether or not the copy is actually done.

    Note that this behaviour is due to change in the next version of C++. In the new standard a const reference initialized from a class prvalue must be bound directly to the reference object; no temporary is permitted to be created in this case and a copy constructor is not used or required.

提交回复
热议问题