c++ - 为什么没有触发 "returning reference to temporary object"编译器警告?

标签 c++ visual-c++ pass-by-reference msvc12

考虑这个简单的代码:

struct Container {
    struct Item {};

    Item operator[](size_t /*index*/) const {
        return Item();
    }

    const Item& f() const {
        return operator[](0);
    }
};

int main()
{
    Container c;
    const Container::Item& item = *c.begin();

    return 0;
}

它有一个错误,令我惊讶的是我只花了大约 30 分钟就注意到了:iterator::operator*() 返回对临时对象的引用。通常它会发出警告。为什么不在这种情况下?

MSVC 2013(v120 工具集),使用 /W4 编译。

P. S. 这是 C4172 ,一级警告。

最佳答案

它看起来像是 Visual Studio 中的一个错误,你可以发现它是针对 VS 2012 报告的,它似乎在 2013 年仍然存在:

https://connect.microsoft.com/VisualStudio/feedback/details/776530/warning-c4172-not-emitted

上面的链接可能与其他链接重复,此错误报告中的示例看起来与您的示例代码完全相同:

// main.cpp

struct A
{
};


struct B
{    
    A a() const {return A();}
};

struct C
{
    A const& a() const
    {
        return B().a();
    }
};

int main()
{
    return 0;
}

关于c++ - 为什么没有触发 "returning reference to temporary object"编译器警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37888301/

相关文章:

c++ - Qt ActiveX 数据类型

c++ - 将对象传递给函数时,如何防止模板化构造函数将类作为参数

c++ - __declspec 分配的范围

Java,为什么我必须直接更改数组的值才能将其作为引用传递?

c++ - 即使关闭预编译 header 并包含 <string>,Visual Studio 也无法识别 stod()

multithreading - 无法从编程书上运行我的代码(c++)

c++ - MSVC 中的 Constexpr 友元函数

python - Cython & C++ : passing by reference

java - 在比较 Java 中的整数包装器时,为什么 128==128 为假,而 127==127 为真?

c++ - 如何获得保证无效的迭代器(对于 vector )?