Home > Backend Development > C++ > Why Does Passing a Temporary Object as a Non-Const Reference in C Cause Compilation Errors?

Why Does Passing a Temporary Object as a Non-Const Reference in C Cause Compilation Errors?

DDD
Release: 2024-12-12 20:07:09
Original
541 people have browsed it

Why Does Passing a Temporary Object as a Non-Const Reference in C   Cause Compilation Errors?

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;
}
Copy after login

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:

  1. Create a temporary variable for the invocation of ProcessFoo:

    Foo foo42(42);
    ProcessFoo(foo42);
    Copy after login
  2. Make ProcessFoo take a const reference:

    void ProcessFoo(const Foo& foo) {
    }
    Copy after login
  3. Allow ProcessFoo to receive Foo by value:

    void ProcessFoo(Foo foo) {
    }
    Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template