Home > Backend Development > C++ > Why Does Visual Studio Compile Non-Constant References to Temporaries While Other Compilers Don't?

Why Does Visual Studio Compile Non-Constant References to Temporaries While Other Compilers Don't?

Linda Hamilton
Release: 2024-12-25 20:24:13
Original
187 people have browsed it

Why Does Visual Studio Compile Non-Constant References to Temporaries While Other Compilers Don't?

Non-Constant Reference Bound to Temporary: Visual Studio Anomaly

This issue arises when compiling code that attempts to bind a non-constant reference to a temporary object. While Visual Studio allows such code to compile, other compilers, like gcc, identify it as a compilation error.

Explanation

In the example provided:

class Zebra {int x;};
Zebra goo() {Zebra z; return z;}
void foo(Zebra &x)
{
    Zebra y;
    x = y;
    foo(goo());
}
Copy after login

The code attempts to bind a non-constant reference (Zebra &x) to a temporary object returned by the function goo(). According to the C standard, this should result in a compile error.

Visual Studio Extension

However, Visual Studio has an old extension that allows for this behavior. This extension essentially treats references to temporary objects as if they were references to non-temporary objects.

This extension was introduced to support legacy code bases. However, it can lead to unexpected behavior and is generally not recommended.

Recommended Approach

To avoid these anomalies, it is best to disable the extension using the /Za compiler flag. This will ensure that the code adheres to the C standard and will be consistently treated by different compilers.

The above is the detailed content of Why Does Visual Studio Compile Non-Constant References to Temporaries While Other Compilers Don'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