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
Barbara StreisandOriginal
2024-12-15 02:19:10287browse

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
}

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);

2. Declaring the Function with a const Reference Parameter

Modify the function declaration to accept a const reference:

void ProcessFoo(const Foo& foo)
{
}

3. Passing by Value

Allow the function to accept the object by value:

void ProcessFoo(Foo foo)
{
}

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!

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
Previous article:Is `coutNext article:Is `cout