簡體   English   中英

為什么我不能將字符指針傳遞給 lambda。 C++ 入門 ex13.44

[英]why i can't pass a char pointer to lambda. C++ Primer 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);
}

該函數將銷毀字符內存,並刪除分配器分配的內存空間。 但是編譯的時候會報錯。

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。 為什么我必須使用&

來自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迭代器的result of dereferencingchar

所以參數應該是char類型。 但是您正在提供/指定一個char*因此您會收到提到的錯誤。

現在,在您的第二個代碼片段中,您通過將 lambda 中的參數類型指定為char& ,因此代碼可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM