簡體   English   中英

為什么使用 __LINE__ 的這段代碼在 MSVC 下可以在 Release 模式下編譯,但不能在 Debug 模式下編譯?

[英]Why does this code using __LINE__ compile under MSVC in Release mode, but not in Debug mode?

考慮這個程序:

#include <iostream>

template<bool Debug = false, int Line = __LINE__>
constexpr int adds(const int& a, const int& b) { 
    if (Debug)
        std::cout << __FUNCTION__ << " called on line " << Line << '\n';
    return (a + b);
}

int main() {
    std::cout << adds(3, 7) << '\n';
    std::cout << adds<true, __LINE__> (5, 9) << '\n';
    return 0;
}

當我嘗試在Debug模式下編譯和構建它時,Visual Studio 2017 正在生成這些編譯器錯誤:

1>------ Build started: Project: Simulator, Configuration: Debug x64 ------
1>main2.cpp
1>c:\***\main2.cpp(12): error C2672: 'adds': no matching overloaded function found
1>c:\***\main2.cpp(12): error C2975: 'Line': invalid template argument for 'adds', expected compile-time constant expression
1>c:\***\main2.cpp(3): note: see declaration of 'Line'
1>Done building project "Simulator.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

但是,當我在Release模式下嘗試此操作時:它編譯、構建、運行並生成適當的 output:

10
adds called on line 12
14

這是潛在的 Visual Studio 2017 錯誤嗎? 如果不是,為什么它在一種模式下工作而不是另一種?

你可以在這里看到它編譯: Compiler Explorer


這是調試和發布模式的命令行標志的副本:

調試

/JMC /permissive- /GS /W3 /Zc:wchar_t /Qspectre /ZI /Gm- /Od /sdl /Fd"x64\Debug\vc141.pdb" /Zc:inline /fp:precise /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /RTC1 /Gd /MDd /std:c++latest /FC /Fa"x64\Debug\" /EHsc /nologo /Fo"x64\Debug\" /Fp"x64\Debug\Simulator.pch" /diagnostics:classic 

發布

/permissive- /GS /GL /W3 /Gy /Zc:wchar_t /Qspectre /Zi /Gm- /O2 /sdl /Fd"x64\Release\vc141.pdb" /Zc:inline /fp:precise /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /Gd /Oi /MD /std:c++latest /FC /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Fp"x64\Release\Simulator.pch" /diagnostics:classic 

好像有人報道過: __LINE__ cannot be used as a argument for constexpr functions

我們在此處的 C++ 團隊中有一個針對此問題的已知錯誤。
[...]
我們已確定此問題不是錯誤。 請參閱喬納森的評論。

喬納森說:

這是編譯器對 Edit-and-Continue 支持的副作用(基本上我們不希望對__LINE__值的更改被認為是抑制 Edit-and-Continue 的“粗魯”編輯):如果你編譯使用/Zi而不是/ZI那么代碼應該編譯(但可執行文件不支持編輯並繼續)。
[...]
該錯誤被認為是一個功能......

來自MSVC 文檔

/ZI選項類似於/Zi ,但它生成的 PDB 文件格式支持“編輯並繼續”功能。 [...] /ZI選項也與__LINE__預定義宏的使用不兼容; /ZI編譯的代碼不能使用__LINE__作為非類型模板參數,盡管__LINE__可以用於宏擴展。


但是,當我在發布模式下嘗試此操作時:它編譯、構建、運行並生成適當的 output:

我猜它的原因是/ZI/Zi標志的差異。 您的發布模式標志有/Zi所以它編譯得很好。

暫無
暫無

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

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