Home >Backend Development >C++ >Why Can't I Pass a Temporary Object to a Non-Const Reference in C ?
Passing Temporary Objects as References Discrepancies
In C , temporary objects can only be passed to references declared as const, by value, or as rvalue references. This restriction prevents inadvertent modification of temporaries, often leading to runtime errors.
Compiler Error
Consider the following code:
class Foo { public: Foo(int x) {}; }; void ProcessFoo(Foo& foo) { } int main() { ProcessFoo(Foo(42)); return 0; }
On Linux and Mac, this code fails to compile with the following error:
error: invalid initialization of non-const reference of type ‘Foo&’ from an rvalue of type ‘Foo’
This error stems from the attempt to pass a temporary Foo object to a non-const reference parameter, which C forbids.
Workarounds
To resolve this issue, one can employ the following workarounds:
Foo foo42(42); ProcessFoo(foo42);
Here, a temporary foo42 variable is created and passed by reference.
void ProcessFoo(const Foo& foo)
This allows temporary objects to be passed due to the const qualifier.
void ProcessFoo(Foo foo)
Passing by value copies the temporary into the function, circumventing the error.
Visual Studio vs. g
Visual Studio's behavior differs from g in this case. MSVC permits passing temporaries to non-const references, potentially introducing subtle runtime issues. This behavior contrasts with g , which strictly adheres to the C standard, prohibiting such practices.
The above is the detailed content of Why Can't I Pass a Temporary Object to a Non-Const Reference in C ?. For more information, please follow other related articles on the PHP Chinese website!