20

此程序在使用 MSVC 编译时打印1 1而不是打印1 2(直到 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(); }

主.cpp:

#include <functional>
#include <iostream>

std::function<int ()> f1();
std::function<int ()> f2();

int main() {
    std::cout << f1()() << " " << f2()() << "\n";
}

就好像 的不同定义F正在破坏 ODR。但是本地类不应该是不同的吗?有趣的是,如果我们F用 lambda 函数替换,则不会发生冲突。

那么这是一个编译器错误还是我误解了一个定义规则?

4

1 回答 1

1

这显然是 MSVC 中的一个错误,因为所有类型都是独一无二的。也许对于在某个函数内部定义的结构(在这种情况下helper),MSVC 在内部将它们视为已定义,helper::F而如果帮助程序是静态的,则应该f1_cpp::helper::F改为执行类似的操作。结果,在链接时,链接器会看到两个同名的内联函数并将它们合并为一个。

2 2如果您不满意,很可能通过重新排序输入文件来获得1 1:)

于 2017-04-11T11:27:46.863 回答