Error: Passing Temporary Object as Reference
In C , attempting to pass a temporary object as a non-const reference may encounter compilation errors. This occurs when a function expects a reference parameter and is invoked with a temporary object.
For instance, consider the following code:
class Foo { public: Foo(int x) {}; }; void ProcessFoo(Foo& foo) { } int main() { ProcessFoo(Foo(42)); return 0; }
This code compiles successfully on some compilers, such as Visual Studio, but fails with errors on others, such as GCC. The error message typically indicates an invalid initialization of the non-const reference parameter from an rvalue type.
Workarounds
To resolve this issue, there are three common workarounds:
Create a temporary variable for the invocation of ProcessFoo:
Foo foo42(42); ProcessFoo(foo42);
Make ProcessFoo take a const reference:
void ProcessFoo(const Foo& foo) { }
Allow ProcessFoo to receive Foo by value:
void ProcessFoo(Foo foo) { }
Reasons for Compilation Errors
C prohibits passing a temporary object to a non-const reference to prevent meaningless operations. A function that takes a non-const reference expects to modify the parameter and return it to the caller. Passing a temporary object defeats this purpose because it cannot be modified and returned.
Compatibility Differences
The reason why the original code compiles on Visual Studio but not on GCC is likely due to differences in compiler configurations. Visual Studio may allow passing temporaries to non-const references as an optimization or for backward compatibility. However, modern C compilers prefer to enforce the language semantics strictly, as implemented in GCC.
The above is the detailed content of Why Does Passing a Temporary Object as a Non-Const Reference in C Cause Compilation Errors?. For more information, please follow other related articles on the PHP Chinese website!