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
<< ", 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
structin front of uses of a struct. Justconst memory_leak_report&would do fine.Second, you tell us how the struct
memory_allocation_recordis defined, but the lambda takes amemory_leak_reportas 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_recordinstead?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:
strip away the irrelevant bits:
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:
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 aconst memory_leak_report&?