Home >Backend Development >C++ >Why Can't I Pass a Temporary Object to a Non-Const Reference in C ?

Why Can't I Pass a Temporary Object to a Non-Const Reference in C ?

DDD
DDDOriginal
2024-12-10 22:29:10246browse

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:

  1. Create a Temporary Variable:
Foo foo42(42);
ProcessFoo(foo42);

Here, a temporary foo42 variable is created and passed by reference.

  1. Pass by Const Reference:
void ProcessFoo(const Foo& foo)

This allows temporary objects to be passed due to the const qualifier.

  1. Pass by Value:
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!

Statement:
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