c++ - 为什么我不能将 char 指针传递给 lambda。C++ 入门 ex13.44
问题描述
我正在编写 std::string 的简化版本。当我编写free
函数时,我使用这样的for_each
函数:
void String::free()
{
std::for_each(element, end, [this](char *c){ alloc.destroy(c); });
alloc.deallocate(element, end-element);
}
该函数将销毁char内存,并删除分配器分配的内存空间。但是编译的时候会报错。
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
正确的答案是改成char *
这样char &
:
void String::free()
{
std::for_each(element, end, [this](char &c){ alloc.destroy(&c); });
alloc.deallocate(element, end-element);
}
我不知道为什么我不能将 char 指针传递给 lambda。为什么我必须使用&
.
解决方案
template< class InputIt, class UnaryFunction >
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );
按顺序将给定的函数对象 f 应用于取消引用范围 [first, last) 中的每个迭代器的结果。
请注意上面引用中对取消引用结果的强调。现在让我们将此引用应用于您的第一个代码片段。在你的情况下:
f
相当于您提供的 lambda
result of dereferencing
迭代器是char
所以参数应该是一个char
类型。但是您正在提供/指定 a char*
,因此您会收到上述错误。
现在在您的第二个代码片段中,您通过在 lambda 中指定参数类型来解决此问题char&
,因此代码可以正常工作。
推荐阅读
- flutter - Flutter 交错网格视图 Pin 图
- swift - 什么决定了返回 JSON 的顺序?
- reinforcement-learning - 如何在强化学习中创造一个关于这个问题的环境?
- javascript - 使用 v-for - vuejs 绑定本地图像
- html - 如何控制图像的位置和大小?
- javascript - 如何编写更好的 async/await + promise 代码?
- c - 使用 dup2 命令重定向
- python - 我正在尝试使用 os.path.getsize 获取文件的大小,但它将大小打印为字节,我想以 MB 为单位打印出来,有什么解决方案吗?
- c - Malloc(1) 正在分配 5 个字节
- javascript - 使用 Expo AppLoading 从 firebase 预加载数据