【发布时间】:2016-11-03 16:21:13
【问题描述】:
这是found here讨论的后续。
以下代码在 gcc 和 clang (live demo) 下编译。这对于//1 行中的情况令人惊讶,因为 lambda 没有捕获任何内容。对于MCR2 的情况,lambda 返回指针本身,我们得到预期的编译时错误(// Will not compile 行)。运算符sizeof的应用与返回指针有何不同?
#include <iostream>
#define MCR1(s) \
([]() { return sizeof(s); })()
#define MCR2(s) \
([]() { return s; })()
int main() {
auto *s= "hello world";
auto x1 = MCR1( s ); //1
auto y1 = MCR1( "hello world" );
// auto x2= MCR2( s ); // Will not compile
auto y2= MCR2( "hello world" );
std::cout << x1 << " " << y1 << '\n';
std::cout // << x2 << " "
<< y2 << '\n';
}
编辑: 继续讨论这里是另一个例子。令人惊讶的是,标记为//2 的行现在可以在 gcc7(开发版)(live demo)下编译。这里的区别是表达式现在被标记为constexpr。
#include <iostream>
#define MCR1(s) \
([]() { return sizeof(s); })()
#define MCR2(s) \
([]() { return s; })()
int main() {
auto constexpr *s= "hello world";
auto constexpr x1= MCR1( s );
auto constexpr y1= MCR1( "hello world" );
auto constexpr x2= MCR2( s ); //2
auto constexpr y2= MCR2( "hello world" );
std::cout << x1 << " " << y1 << '\n';
std::cout << x2 << " " << y2 << '\n';
}
【问题讨论】:
-
你原来的例子godbolt.org/g/eNVaWh的情况是不是更惊人?你在 lambda 中返回 s,它仍然可以编译。
-
@Rumburak 你又是对的。添加了另一个示例。