VS2010中lambda表达式的不同大小?
出于好奇,我测试了lamba表达式的大小。我的第一个想法是,它们有 4
字节大,就像函数指针一样。奇怪的是,我的第一个测试的输出是 1
:
auto my_lambda = [&]() -> void {};
std::cout << sizeof(my_lambda) << std::endl;
然后我在 lambda 内部进行了一些计算测试,输出仍然是 1
:
auto my_lambda2 = [&]() -> void {int i=5, j=23; std::cout << i*j << std::endl;};
std::cout << sizeof(my_lambda2) << std::endl;
我的下一个想法有点随机,但是输出终于改变了,显示等待的 4
:
auto my_lambda3 = [&]() -> void {std::cout << sizeof(my_lambda2) << std::endl;};
std::cout << sizeof(my_lambda3) << std::endl;
至少在 Visual Studio 2010 中。Ideone 仍然显示 1
作为输出。
我知道标准规则,即 lambda 表达式不能出现在未评估的上下文中,但据我所知,这只适用于直接使用 lambda,例如sizeof([&]() -> void {std::cout << "禁止。" << std::endl;})
VS2010 提示我编译器错误。 有人知道发生了什么事吗?
Out of curiosity, I tested the size of a lamba expression. My first thought was, that they'd be 4
bytes big, like a function pointer. Strangely, the output of my first test was 1
:
auto my_lambda = [&]() -> void {};
std::cout << sizeof(my_lambda) << std::endl;
Then I tested with some calculations inside the lambda, the output still being 1
:
auto my_lambda2 = [&]() -> void {int i=5, j=23; std::cout << i*j << std::endl;};
std::cout << sizeof(my_lambda2) << std::endl;
My next idea was kinda random, but the output finally changed, displaying the awaited 4
:
auto my_lambda3 = [&]() -> void {std::cout << sizeof(my_lambda2) << std::endl;};
std::cout << sizeof(my_lambda3) << std::endl;
At least in Visual Studio 2010. Ideone still display 1
as the output.
I know of the standard rule, that a lambda expression cannot appear in an unevaluated context, but afaik that only counts for direct lambda use likesizeof([&]() -> void {std::cout << "Forbidden." << std::endl;})
on which VS2010 prompts me with a compiler error.
Anyone got an idea what's going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
感谢@Hans Passant 在问题下的评论,找到了解决方案。我原来的方法是错误的,因为我认为每个对象都会被 lambda 捕获,但事实并非如此,只有封闭范围内的对象才会被捕获,并且只有在使用它们时才会被捕获。
对于所有捕获的对象,都使用 4 个字节(引用的大小)。
Thanks to @Hans Passant's comment under the question, the solution was found. My original approach was wrong in the fact that I thought every object would be captured by the lambda, but that isn't the case, only those in the enclosing scope are, and only if they are used.
And for everyone of those captured objects, 4 bytes are used (size of the reference).
Visual Studio 可能不会将 lambda 对象实现为函数。你可能会拿回一个物体。谁知道它是什么样子的。如果您真的感兴趣,您可以随时使用调试器查看变量并看看它们是什么样子......如果它允许的话。
Visual Studio probably doesn't implement lambda objects as functions. You're probably getting an object back. Who knows what it looks like. If you're truly interested you could always look at your variables with a debugger and see what they look like...if it'll let you.