根据Lambda表达式:
如果变量 (...) 是 constexpr 并且没有可变成员,则 lambda 表达式可以读取变量的值而不捕获它
在下面的例子中我相信
constexpr int cInt = 1234;
就是这样一个变量。
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using testing::Eq;
using testing::Matches;
TEST(xxx, zzz)
{
constexpr int cInt = 1234;
auto scenario = []()
{
if (cInt == 1234) { std::cout << "1234 check\n"; }
if (Matches(Eq(1234))(cInt)) { std::cout << "1234 matcher check\n"; }
};
}
然而,如果我在 gmock 匹配器表达式
constexpr
中使用 Matches(Eq(1234))(cInt))
变量,最新的 gcc 和 clang 都会拒绝该代码。 演示。
<source>:13:31: error: 'cInt' is not captured
13 | if (Matches(Eq(1234))(cInt)) { std::cout << "1234 matcher check\n"; }
| ^~~~
<source>:10:22: note: the lambda has no capture-default
10 | auto scenario = []()
| ^
<source>:9:19: note: 'constexpr const int cInt' declared here
9 | constexpr int cInt = 1234;
对于 gcc 7.3 此代码没问题。
MSVC 甚至拒绝这一点:
constexpr int cInt = 1234;
auto scenario = []()
{
if (cInt == 1234) { std::cout << "1234 check\n"; }
};
但它是微软软件,所以我并不感到惊讶。
这是编译器中的错误,还是 googletest 方面的问题?我不确定是否应该报告以及在哪里报告。
costexpr不需要是编译时对象,它可以是编译时对象
我过去在使用 MSVC 时遇到过这种情况,它通过将我的 constexp 值转换为 const 值给出了完全相同的故事(在调试器中检查代码时发现了这种行为,constexpr值的内存是由 MSVC 在堆栈上分配的),所以这就是为什么这里它没有被 lambda 捕获,因为它不是全局的
正如您已经建议的那样,您应该将其标记为 static constexpr 以在 lambda 函数中显示该值