Passing Temporary Objects as References in C
In C , a minimal code snippet such as the following can cause compilation errors on Linux and Mac platforms:
class Foo { public: Foo(int x) {} }; void ProcessFoo(Foo& foo) { } int main() { ProcessFoo(Foo(42)); return 0; }
Compilation Error:
Compiling the above code results in the following error:
newfile.cpp: In function ‘int main()’: newfile.cpp:23:23: error: invalid initialization of non-const reference of type ‘Foo&’ from an rvalue of type ‘Foo’ ProcessFoo(Foo(42)); ^ newfile.cpp:14:6: note: in passing argument 1 of ‘void ProcessFoo(Foo&)’ void ProcessFoo(Foo& foo)
Why the Error Occurs:
By design, C prohibits passing a temporary object to a non-const reference parameter. This restriction is intended to prevent potential misunderstandings and errors. When a function declares a non-const reference parameter, it signifies its intent to modify the object and return it to the caller. Passing a temporary to such a parameter is illogical, as it will be destroyed once the function returns.
Workarounds:
To resolve this compilation error, consider the following workarounds:
Foo foo42(42); ProcessFoo(foo42);
void ProcessFoo(const Foo& foo)
void ProcessFoo(Foo foo)
Why MSVC Allows It:
It's unclear why Microsoft Visual Studio (MSVC) allows this code to compile while g does not. Potentially, MSVC has a different interpretation of the C standard in this regard. It's generally recommended to follow the standard to ensure consistent behavior across different compilers.
The above is the detailed content of Why Does Passing a Temporary Object to a Non-Const Reference Fail in C ?. For more information, please follow other related articles on the PHP Chinese website!