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
Release: 2024-12-10 22:29:10
Original
245 people have browsed it

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

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’
Copy after login

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

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

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

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

  1. Pass by Value:
void ProcessFoo(Foo foo)
Copy after login

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!

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