1

I have some class that can receive things using an overloaded << operator, and also accept some settings - conveniently applied by methods returning *this so this can be chained.

However, on Microsoft Visual C++ (latest) with /std:c++latest the warning C4866 (compiler may not enforce left-to-right evaluation) is suddenly raised. Any idea why and how to prevent this?

The argument (here to constructor sv_holder must be some more complex type - it works without warnings for pod type).

#include <iostream>
#include <string_view>

class sv_holder
{
public:
    sv_holder(std::string_view v) : m_sv(v) {}
    std::string_view m_sv;
};

class C
{
public:
    C() {}

    C &accept(const sv_holder &) { return *this; }

    template <typename T> C &operator<<(const T &t)
    {
        std::cout << t;
        return *this;
    }
};

void fail_function()
{
    C c;
    c.accept(sv_holder(__FILE__)) << "stream test";
}
schroder
  • 181
  • 1
  • 3
  • 1
    It's really a compiler non-conformance warning. The C++ Standard from C++17 onwards requires operator arguments to be evaluated left-to-right. MSVC is not doing this, so it's issuing a warning in case the code relies on left-to-right evaluation of operator arguments. _"...There are two cases in which the compiler is unable to guarantee this order:..."_ https://learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/c4866?view=msvc-160 – Richard Critten Feb 13 '21 at 12:49
  • But, they continue to write: If the order of evaluation must be left-to-right, consider whether you can pass the elements by const reference instead. In example above, is it the transitive string_view by value that matters? - In fact it is. Still this looks to me like a compiler implementation limitation. – schroder Feb 13 '21 at 14:44

0 Answers0