Val*_*lea 20 c++ one-definition-rule visual-c++
打印此程序1 1而不是1 2使用MSVC编译时(直到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(); }
Run Code Online (Sandbox Code Playgroud)
f2.cpp:
#include <functional>
static std::function<int ()> helper() {
struct F { int operator()() { return 2; } };
return F();
}
std::function<int ()> f2() { return helper(); }
Run Code Online (Sandbox Code Playgroud)
main.cpp中:
#include <functional>
#include <iostream>
std::function<int ()> f1();
std::function<int ()> f2();
int main() {
std::cout << f1()() << " " << f2()() << "\n";
}
Run Code Online (Sandbox Code Playgroud)
就好像不同的定义F正在破坏ODR.但本地课程不应该是明显的吗?有趣的是,如果我们F用lambda函数替换它就没有冲突.
那么这是一个编译器错误还是我误解了一个定义规则?
这显然是 MSVC 中的一个错误,因为所有类型都是唯一的。也许对于在某个函数内部定义的结构(在本例中helper),MSVC 在内部将它们视为定义为,helper::F而如果 helper 是静态的,则应该执行类似的操作f1_cpp::helper::F。因此,在链接时链接器会看到两个名称相同的内联函数并将它们合并为一个。
2 2如果您不满意,最有可能通过重新排序输入文件来获得1 1:)
| 归档时间: |
|
| 查看次数: |
325 次 |
| 最近记录: |