When attempting to pass a temporary object as a non-const reference, such as in the following code:
void ProcessFoo(Foo& foo) { } int main() { ProcessFoo(Foo(42)); // Error: Can't pass temporary object as reference }
compilers like g and clang raise an error. This occurs because, by design, C restricts passing temporaries to const references, value parameters, or rvalue references.
The rationale behind this restriction is that functions receiving non-const reference parameters intend to modify those parameters and return them to the caller. Passing a temporary in this scenario is considered nonsensical and likely indicative of an error.
To resolve this issue, several workarounds are available:
1. Using a Temporary Variable
Create a temporary variable and pass it to the function as an argument:
Foo foo42(42); ProcessFoo(foo42);
2. Declaring the Function with a const Reference Parameter
Modify the function declaration to accept a const reference:
void ProcessFoo(const Foo& foo) { }
3. Passing by Value
Allow the function to accept the object by value:
void ProcessFoo(Foo foo) { }
Visual Studio allows this original code due to a less restrictive compiler implementation.
The above is the detailed content of Why Can't I Pass a Temporary Object as a Non-Const Reference in C ?. For more information, please follow other related articles on the PHP Chinese website!