I am writing a simplified version of std::string. When i'm writing the free
function, i use the for_each
function like this:
void String::free()
{
std::for_each(element, end, [this](char *c){ alloc.destroy(c); });
alloc.deallocate(element, end-element);
}
This function will destory the char memory, and delete the memory space allocated by allocator. But it will be error when i compile it.
In file included from /usr/include/c++/9/algorithm:62,
from 13_44_String.cpp:2:
/usr/include/c++/9/bits/stl_algo.h: In instantiation of ‘_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = char*; _Funct = String::free()::<lambda(char*)>]’:
13_44_String.cpp:20:69: required from here
/usr/include/c++/9/bits/stl_algo.h:3876:5: error: no match for call to ‘(String::free()::<lambda(char*)>) (char&)’
3876 | __f(*__first);
| ~~~^~~~~~~~~~
13_44_String.cpp:20:33: note: candidate: ‘String::free()::<lambda(char*)>’ <near match>
20 | std::for_each(element, end, [this](char *c){ alloc.destroy(c); });
| ^
13_44_String.cpp:20:33: note: conversion of argument 1 would be ill-formed:
In file included from /usr/include/c++/9/algorithm:62,
from 13_44_String.cpp:2:
/usr/include/c++/9/bits/stl_algo.h:3876:5: error: invalid conversion from ‘char’ to ‘char*’ [-fpermissive]
3876 | __f(*__first);
| ~~~^~~~~~~~~~
| |
| char
The right answer is change char *
to char &
like this:
void String::free()
{
std::for_each(element, end, [this](char &c){ alloc.destroy(&c); });
alloc.deallocate(element, end-element);
}
I do not know why i can't pass a char pointer to a lambda. Why i must use the &
.