How can you modify an object without calling member functions?

后端 未结 7 2446
不知归路
不知归路 2021-02-13 15:41

At 3.10/10, the standard says:

An lvalue for an object is necessary in order to modify the object except that an rvalue of class type can also be used to

7条回答
  •  闹比i
    闹比i (楼主)
    2021-02-13 16:11

    How can one modify an object [that's specified by an rvalue expression] without calling a member function?

    I know of only one way to do that, namely to bind the object to a reference to const, and then cast away the const-ness.

    E.g.

    template< class Type >
    Type& tempRef( Type const& o ) { return const_cast< Type& >( o ); }
    
    struct S { int x; };
    
    int main()
    { tempRef( S() ).x = 3; }
    

    This is because a temporary object is not const itself unless it is of const type, so the example above does not cast away original const-ness (which would be UB).

    EDIT, added: Luc Danton’s answer showed another (non-general) way, namely where the temporary's construction stores some reference or pointer to the object in some accessible location.

    Cheers & hth.,

提交回复
热议问题