Why Non-Const References to Temporary Objects Are Prohibited
C forbids assigning temporary objects to non-const references. This restriction stems from the fact that temporary objects vanish after the statement in which they are created. Allowing non-const references to temporary objects could lead to undefined behavior.
Consider the following code:
String& a = String("test"); // Error
This code attempts to assign a temporary String object to a non-const reference a. However, this is not allowed because a is not a const reference and temporary objects cannot be modified.
Some common reasons for this restriction include:
C allows reading from temporary objects but not writing to them because reading does not alter the state of the object. However, writing to a temporary object could have unexpected consequences, as the object may be destroyed before the write operation completes.
Therefore, to prevent these potential problems, C restricts non-const references to temporary objects, while still allowing const references for safe reading purposes. This restriction helps ensure program correctness and prevents undefined behavior that could result from modifying temporary objects.
The above is the detailed content of Why Can't I Assign Temporary Objects to Non-Const References in C ?. For more information, please follow other related articles on the PHP Chinese website!