c++ lambda expression help
I'm a bit new to c++0x, can anyone explain to me why the following fail to compile:
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
<< "开发者_如何学Python, size:" << rec.size << std::endl;
});
}
where allocation_records is defined as: std::list<struct memory_allocation_record> allocation_records
and memory_allocation_record
is a simple C style data structure.
struct memory_allocation_record {
const char *func;
const char *file;
unsigned int line;
unsigned int size;
unsigned long address;
};
I've tried compiling it with: g++ -Wall -g -o alloc main.cpp -std=c++0x
The errors I get are: In function ג_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = std::_List_iterator, _Funct = memory_leak_report()::]
error: no match for call to (memory_leak_report()::) (memory_allocation_record&)
note: candidates are: void (*)(const memory_leak_report()::memory_leak_report&)
First, In C++, you don't need to (and it's usually considered bad style) put struct
in front of uses of a struct. Just const memory_leak_report&
would do fine.
Second, you tell us how the struct memory_allocation_record
is defined, but the lambda takes a memory_leak_report
as its parameter, which, as far as I can see, is a function.
is that your error? Was the lambda supposed to take a memory_allocation_record
instead?
Which brings us to the last point, of course. If you get an error, don't you think it'd be relevant to tell us what that error is? Otherwise, we have to guess at what we think might be a problem in your code.
Edit
Ok, as I suspected, that seems to be the problem. I can recommend actually reading the compiler's errors. That's why they're there. ;)
Take the first line of the error:
/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&)
strip away the irrelevant bits:
no match for call to <somethingwithlambdas> (memory_allocation_record&)
Now, because this is a lambda, the type is a bit hairy, but ultimately, it's talking about a function call, and so the last parentheses describe the parameter. In other words, it tries to call a function with a memory_allocation_record&
as its parameter, but is unable to find a matching function.
Instead, it found the candidate described in the second line:
candidates are: void (*)(const memory_leak_report()::memory_leak_report&) <conversion>
So, the candidate it actually found takes a const memory_leak_report&
as its parameter.
Now you just need to compare the two. What could it mean, when the compiler tries to pass a memory_allocation_record&
to a function that expects a const memory_leak_report&
?
精彩评论