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

Why Does Visual Studio Allow Non-Const References to Bind to Temporary Objects?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-21 15:26:10278browse

Why Does Visual Studio Allow Non-Const References to Bind to Temporary Objects?

Visual Studio Bug: Non-Const Reference Bound to Temporary Object

The given code snippet illustrates a peculiar behavior observed in Visual Studio:

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

Visual Studio allows this code to compile without errors, while gcc raises a compile error. This behavior becomes even more puzzling when a typedef is used to represent Zebra as int, as Visual Studio then detects the issue.

This behavior is driven by an old Visual Studio extension. As documented in Microsoft's bug report, "Temporary Objects Can be Bound to Non-Const References," Visual Studio permits non-const references to be bound to temporary objects.

However, this extension can be disabled using the /Za compiler flag, which will make the code snippet in question an error. Additionally, a level 4 warning (enabled with /W4) is available to flag this issue.

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