![](/img/trans.png)
[英]Operator new behaves differently in Debug mode than in Release mode in MSVC
[英]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.