Why is only a const reference allowed for temporary objects in C ?
In C , assignment of temporary objects is permitted solely to const references, while non-const references are forbidden. This constraint has prompted numerous questions, particularly regarding the potential for modifying temporary objects.
As it is widely acknowledged, temporary objects are ephemeral and disappear as soon as the statement containing their creation ends. This raises a valid concern: why is modification restricted while reading is allowed?
To comprehend this discrepancy, consider a hypothetical situation involving a function parameter:
If non-const references were allowed for temporary parameters, the behavior of this code would be peculiar. Despite passing an int argument by reference, the value of i remains unchanged after invoking inc. This would cause unanticipated and illogical outcomes.
Allowing const references, however, guarantees that the temporary object passed to the function parameter cannot be accidentally modified. This prevents the possibility of unexpected behavior and ensures that the intent of using a const reference is upheld.
The above is the detailed content of Why Can't I Pass Temporary Objects to Non-Const References in C ?. For more information, please follow other related articles on the PHP Chinese website!