Passing Temporary Objects as References
In C , using a temporary object as a reference can lead to unexpected behavior. To avoid this, the compiler enforces restrictions on passing temporary objects to reference parameters.
When compiling the code provided in the initial query:
class Foo { public: Foo(int x) {}; }; void ProcessFoo(Foo& foo) {}; int main() { ProcessFoo(Foo(42)); return 0; }
the error arises because the temporary Foo(42) object is being passed to a non-const reference parameter (ProcessFoo(Foo& foo)). By design, C disallows this practice.
Workarounds:
The suggested workarounds alleviate the issue by:
Creating a Temporary Variable: Assigning the temporary object to a variable and then passing it as a reference:
Foo foo42(42); ProcessFoo(foo42);
Using a Const Reference: Modifying ProcessFoo to take a const reference (ProcessFoo(const Foo& foo)), which allows it to accept temporary objects:
void ProcessFoo(const Foo& foo) {}; ProcessFoo(Foo(42));
Passing by Value: Allowing ProcessFoo to receive the object by value (ProcessFoo(Foo foo)), which avoids the reference restriction:
void ProcessFoo(Foo foo) {}; ProcessFoo(Foo(42));
Compiler Discrepancy:
The behavior difference between Microsoft Visual Studio and GNU C (g ) is likely due to different default settings. By default, g enforces stricter compliance with the C standard, while Visual Studio may allow certain deviations. This can lead to errors being generated in one compiler but not the other.
The above is the detailed content of Why Can't I Pass a Temporary C Object to a Non-Const Reference?. For more information, please follow other related articles on the PHP Chinese website!