当访问变量a里面的"run"lambda时,我观察到地址与main中的'a'不同.这种情况只发生在这种lambda嵌套中.这是预期的吗?我只能通过这种非平凡的嵌套来重现.
我用lambda中的gdb检查地址,这个 - > __ a
用gdb打印lambda内部产生垃圾,而lambda在lambda对象中有捕获的参数,这就是为什么这个 - > __ a的地址不同于:
(gdb) p &a
$5 = (unsigned int *) 0x7fffffffdce8
(gdb) p *this
$6 = {__a = @0x7fffffffdde8}
(gdb) p a
$7 = 4207233
(gdb) p this->__a
$8 = (unsigned int &) @0x7fffffffdde8: 2
Run Code Online (Sandbox Code Playgroud)
当lambda没有嵌套时,我记得观察同一个地址.
目前在g ++ - 4.5(Debian 4.5.3-3)4.5.3和g ++ - 4.6(Debian 4.6.0-10)4.6.1 20110526(预发布)中看到了这种行为
#include <string>
#include <cstdlib>
#include <cassert>
#include <vector>
#include <stdexcept>
#include <stdint.h>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[])
{
unsigned a = 0;
vector<int> vi = {0, 1, 2, 3, 4 };
auto run = [&](int& i) {
// inside this lambda &a is not the same as the &a in the first line
cout << "i: " << i << endl;
a++;
cout << "a: " << a << endl;
};
for_each(vi.begin(), vi.end(), [&](int& xi) {
run(xi);
});
cout << "a: " << a << endl;
}
Run Code Online (Sandbox Code Playgroud)
我填写了与此问题相关的以下bug报告:http://gcc.gnu.org/bugzilla/show_bug.cgi?id = 49651
spr*_*aff -1
这是一个简单的三段论:
&a产生正确的值。this->__a会产生不同的价值。因此
this->__a与以下不同&a那么我们如何解释这一点呢?可能是包含 的描述的this->__a对象,编译器可能已将任何类型的元数据放入其中以进行调试或任何其他目的。a
| 归档时间: |
|
| 查看次数: |
481 次 |
| 最近记录: |