Home > Backend Development > C++ > Why Does Passing a Temporary Object to a Non-Const Reference Fail in C ?

Why Does Passing a Temporary Object to a Non-Const Reference Fail in C ?

Patricia Arquette
Release: 2024-12-05 09:07:11
Original
352 people have browsed it

Why Does Passing a Temporary Object to a Non-Const Reference Fail in C  ?

Passing Temporary Objects as References in C

In C , a minimal code snippet such as the following can cause compilation errors on Linux and Mac platforms:

class Foo
{
public:
    Foo(int x) {}
};

void ProcessFoo(Foo& foo)
{
}

int main()
{
    ProcessFoo(Foo(42));
    return 0;
}
Copy after login

Compilation Error:

Compiling the above code results in the following error:

newfile.cpp: In function ‘int main()’:
newfile.cpp:23:23: error: invalid initialization of non-const reference of type ‘Foo&’ from an rvalue of type ‘Foo’
     ProcessFoo(Foo(42));
                       ^
newfile.cpp:14:6: note: in passing argument 1 of ‘void ProcessFoo(Foo&)’
 void ProcessFoo(Foo& foo)
Copy after login

Why the Error Occurs:

By design, C prohibits passing a temporary object to a non-const reference parameter. This restriction is intended to prevent potential misunderstandings and errors. When a function declares a non-const reference parameter, it signifies its intent to modify the object and return it to the caller. Passing a temporary to such a parameter is illogical, as it will be destroyed once the function returns.

Workarounds:

To resolve this compilation error, consider the following workarounds:

  • Create a Temporary Variable: Create a non-temporary variable that holds the temporary object before passing it to the function:
Foo foo42(42);
ProcessFoo(foo42);
Copy after login
  • Use a Const Reference: Modify the function to take a const reference parameter:
void ProcessFoo(const Foo& foo)
Copy after login
  • Pass by Value: Allow the function to take the object as a value parameter:
void ProcessFoo(Foo foo)
Copy after login

Why MSVC Allows It:

It's unclear why Microsoft Visual Studio (MSVC) allows this code to compile while g does not. Potentially, MSVC has a different interpretation of the C standard in this regard. It's generally recommended to follow the standard to ensure consistent behavior across different compilers.

The above is the detailed content of Why Does Passing a Temporary Object to a Non-Const Reference Fail 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