This program prints 1 1
instead of 1 2
when compiled with MSVC (up to VS 2015).
f1.cpp:
#include <functional>
static std::function<int ()> helper() {
struct F { int operator()() { return 1; } };
return F();
}
std::function<int ()> f1() { return helper(); }
f2.cpp:
#include <functional>
static std::function<int ()> helper() {
struct F { int operator()() { return 2; } };
return F();
}
std::function<int ()> f2() { return helper(); }
main.cpp:
#include <functional>
#include <iostream>
std::function<int ()> f1();
std::function<int ()> f2();
int main() {
std::cout << f1()() << " " << f2()() << "\n";
}
It's as if the different definitions of F
are breaking ODR. But shouldn't local classes be distinct? Interestingly, if we replace F
with lambda functions there is no conflict.
So is this a compiler bug or am I misunderstanding the one definition rule?
static
and use an unnamed namespace. – Spathosehelper()
is put in anonymous namespace then the conflict goes away. – Doorsill1 2
now. I swear I was getting1 1
when I wrote that comment. :P – Spathosef1.cpp
andf2.cpp
had changed. – Spathose/opt:noicf
fixes it or not, it seems like a stretch but I have seen some interesting breaks due to this so it is worth a try. – Colet/link /opt:noicf
. I assume folding applies only to functions with identical definitions, which is not the case here. – DoorsillF
out of the function and into an anonymous namespace in your source files. – Rainbow