c++ lambda表达式帮助

c++ lambda expression help

本文关键字:帮助 表达式 lambda c++      更新时间:2023-10-16

我对c++0x有点陌生,谁能给我解释一下为什么下面的编译失败:

void memory_leak_report()
{
    std::cout.flags(std::ios::showbase);
    std::for_each(allocation_records.begin(), allocation_records.end(),
                  [] (const struct memory_leak_report& rec) {
                      std::cout << "memory leak at: " << rec.file << ": line " << rec.line
                                << std::hex << ", address: " << rec.address << std::dec
                                << ", size:" << rec.size << std::endl;
    });
}
std::list<struct memory_allocation_record> allocation_recordsmemory_allocation_record是一个简单的C风格数据结构。
struct memory_allocation_record {
    const char *func;
    const char *file;
    unsigned int line;
    unsigned int size;
    unsigned long address;
};

我试过编译它:g++ -Wall -g -o alloc main.cpp -std=c++0x

我得到的错误是:在函数中,std::for_each(_IIter, _IIter, _Funct) [with _IIter = std::_List_iterator, _Funct = memory_leak_report()::]

错误:没有匹配调用(memory_leak_report()::) (memory_allocation_record&)

注意:候选对象是:void (*)(const memory_leak_report()::memory_leak_report&)

首先,在c++中,你不需要(通常被认为是糟糕的风格)把struct放在结构体的使用前面。只要const memory_leak_report&就可以了。

第二,你告诉我们结构体memory_allocation_record是如何定义的,但是lambda接受memory_leak_report作为它的参数,据我所知,是一个函数。这是你的错误吗?是应该采取一个memory_allocation_record代替?

这就引出了最后一点。如果出现错误,你不觉得应该告诉我们错误是什么吗?否则,我们必须猜测我们认为可能是代码中的问题。

编辑
好吧,正如我所料,这似乎就是问题所在。我建议实际阅读编译器的错误。这就是他们在那里的原因。;)

取错误的第一行:

/usr/include/c++/4.5/bits/stl_algo.h:4185:2: error: no match for call to ג(memory_leak_report()::<lambda(const memory_leak_report()::memory_leak_report&)>) (memory_allocation_record&)

去掉不相关的位:

no match for call to <somethingwithlambdas> (memory_allocation_record&)

现在,因为这是一个lambda,类型有点复杂,但最终,它讨论的是一个函数调用,所以最后一个括号描述了参数。换句话说,它试图调用一个以memory_allocation_record&作为参数的函数,但无法找到匹配的函数。

相反,它找到了第二行中描述的候选对象:
candidates are: void (*)(const memory_leak_report()::memory_leak_report&) <conversion>

因此,它实际上找到的候选const memory_leak_report&作为其参数

现在你只需要比较这两个。当编译器试图将memory_allocation_record&传递给期望const memory_leak_report&的函数时,这意味着什么?