簡體   English   中英

MSVC中的ODR錯誤?

[英]ODR bug in MSVC?

當使用MSVC(直到VS 2015)編譯時,該程序打印1 1而不是1 2

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

就好像F的不同定義打破ODR一樣。 但本地課程不應該是明顯的嗎? 有趣的是,如果我們用lambda函數替換F ,就沒有沖突。

那么這是一個編譯器錯誤還是我誤解了一個定義規則?

這顯然是MSVC中的一個錯誤,因為所有類型都是唯一的。 也許對於在某個函數內部定義的結構(在這種情況下為helper ),MSVC在內部將它們視為將它們定義為helper::F而如果helper是靜態的,它應該完成類似於f1_cpp::helper::F 因此,鏈接時鏈接器會看到兩個名稱相同的內聯函數,並將它們合並為一個。

最有可能通過重新排序輸入文件,如果你對1 1不滿意,你可以獲得2 2 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM