Home > Backend Development > C++ > Why Does Visual Studio Allow Non-Const References to Bind to Temporary Objects While GCC Doesn't?

Why Does Visual Studio Allow Non-Const References to Bind to Temporary Objects While GCC Doesn't?

Patricia Arquette
Release: 2024-12-22 19:58:10
Original
762 people have browsed it

Why Does Visual Studio Allow Non-Const References to Bind to Temporary Objects While GCC Doesn't?

Error: Non-const Reference Bound to Temporary in Visual Studio

GCC raises an error when assigning a temporary object to a non-const reference. Surprisingly, Visual Studio allows this. Why the discrepancy?

The explanation lies in an old extension in Visual Studio. As noted in a bug report: "Temporary Objects Can be Bound to Non-Const References," Visual Studio allows temporary objects to be bound to non-const references, even though it can result in undefined behavior.

This behavior has been controversial. One response to the bug report notes that there is a level 4 warning for this error, which can be enabled with the "/W4" compiler flag.

However, there is a way to make this an error in Visual Studio: disable language extensions with the "/Za" flag. This is a useful workaround if you want to adhere to strict C standards and avoid potentially problematic code behavior.

To illustrate, consider the following example:

class Zebra { int x; };
Zebra goo() { Zebra z; return z; }
void foo(Zebra &x)
{
    Zebra y;
    x = y;
    foo(goo()); // Error in GCC, allowed in Visual Studio
}
Copy after login

In Visual Studio, this code will compile without errors. However, in GCC, it will generate a compile error due to the temporary object being assigned to a non-const reference.

The above is the detailed content of Why Does Visual Studio Allow Non-Const References to Bind to Temporary Objects While GCC Doesn't?. 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