首页 > 解决方案 > 为什么我不能将 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。为什么我必须使用&.

标签: c++

解决方案


来自std::for_each 文档

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&,因此代码可以正常工作。


推荐阅读