为什么 MSVC _count_of 实现会在 sizeof 的结果中加 0?
Why does the MSVC _count_of implementation add 0 to the result of sizeof?
我一直在阅读 _countof
macro in MSVC and found a detail I can't explain. It's implemented via a __crt_countof
macro which on C++ is expanded to (sizeof(*__countof_helper(_Array)) + 0)
(here's 的相关代码的实现 header)。为什么 + 0
在那里?没有它会有什么问题?
添加 + 0
是为了防止 可能 出现 Most Vexing Parse!没有它,像 sizeof(*__countof_helper(_Array))
这样的表达式在某些情况下可能 被视为函数声明。
编辑:我目前正在尝试编写示例上下文(根据评论中的要求)。与此同时,这个大大简化的'equivalent'(我实际遇到过的东西)可能会有所帮助:
#include <iostream>
#include <vector>
int main() {
int num = 2;
// std::vector<char> vec(size_t(num)); // Won't compile - Most Vexing Parse
std::vector<char> vec(size_t(num) + 0); // Compiles - no longer a func decl!
vec[0] = 'a';
vec[1] = 'b';
std::cout << vec[0] << ' ' << vec[1] << std::endl;
return 0;
}
我一直在阅读 _countof
macro in MSVC and found a detail I can't explain. It's implemented via a __crt_countof
macro which on C++ is expanded to (sizeof(*__countof_helper(_Array)) + 0)
(here's 的相关代码的实现 header)。为什么 + 0
在那里?没有它会有什么问题?
添加 + 0
是为了防止 可能 出现 Most Vexing Parse!没有它,像 sizeof(*__countof_helper(_Array))
这样的表达式在某些情况下可能 被视为函数声明。
编辑:我目前正在尝试编写示例上下文(根据评论中的要求)。与此同时,这个大大简化的'equivalent'(我实际遇到过的东西)可能会有所帮助:
#include <iostream>
#include <vector>
int main() {
int num = 2;
// std::vector<char> vec(size_t(num)); // Won't compile - Most Vexing Parse
std::vector<char> vec(size_t(num) + 0); // Compiles - no longer a func decl!
vec[0] = 'a';
vec[1] = 'b';
std::cout << vec[0] << ' ' << vec[1] << std::endl;
return 0;
}