c++visual-c++pass-by-referencemsvc12

Why is the "returning reference to temporary object" compiler warning not triggered?


Consider this simple code:

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;
}

It has a bug, and I'm surprised it only took me about 30 minutes to notice: iterator::operator*() returns a reference to temporary object. Usually it throws a warning. Why not in this case?

MSVC 2013 (v120 toolset), compiled with /W4.

P. S. This is C4172, a level 1 warning.


Solution

  • It looks like it is a bug in Visual Studio, you can find it was reported for VS 2012 and it appears it was still present in 2013:

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

    Above link might be a duplicate of some other, the example from this bug report looks quite the same as your sample code:

    // main.cpp
    
    struct A
    {
    };
    
    
    struct B
    {    
        A a() const {return A();}
    };
    
    struct C
    {
        A const& a() const
        {
            return B().a();
        }
    };
    
    int main()
    {
        return 0;
    }