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

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

Barbara Streisand
Release: 2024-12-15 02:19:10
Original
285 people have browsed it

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

Passing a Temporary Object as Reference

When attempting to pass a temporary object as a non-const reference, such as in the following code:

void ProcessFoo(Foo& foo)
{
}

int main()
{
    ProcessFoo(Foo(42)); // Error: Can't pass temporary object as reference
}
Copy after login

compilers like g and clang raise an error. This occurs because, by design, C restricts passing temporaries to const references, value parameters, or rvalue references.

The rationale behind this restriction is that functions receiving non-const reference parameters intend to modify those parameters and return them to the caller. Passing a temporary in this scenario is considered nonsensical and likely indicative of an error.

To resolve this issue, several workarounds are available:

1. Using a Temporary Variable

Create a temporary variable and pass it to the function as an argument:

Foo foo42(42);
ProcessFoo(foo42);
Copy after login

2. Declaring the Function with a const Reference Parameter

Modify the function declaration to accept a const reference:

void ProcessFoo(const Foo& foo)
{
}
Copy after login

3. Passing by Value

Allow the function to accept the object by value:

void ProcessFoo(Foo foo)
{
}
Copy after login

Visual Studio allows this original code due to a less restrictive compiler implementation.

The above is the detailed content of Why Can't I Pass a Temporary Object as 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template