Std::переместить захваченный unique_ptr внутри лямбдыC++

Программы на C++. Форум разработчиков
Ответить
Anonymous
 Std::переместить захваченный unique_ptr внутри лямбды

Сообщение Anonymous »

Я хотел захватить std::unique_ptr в лямбду, а затем переместить его в другую функцию внутри лямбды, но мои два минимальных примера не удалось скомпилировать, и я не знаю почему.
Может кто-нибудь объяснить мне, почему он пытается создать копию, хотя я пытаюсь переместить ее в первом примере, и откуда берется квалификатор const во втором примере?Первый пример (функция принимает std::unique_ptr по значению):
#include

void sink(std::unique_ptr p) {
// Do something with `p`
}

int main() {
auto p = std::make_unique(42);
auto f = [p = std::move(p)](){
sink(std::move(p));
};
f();
return 0;
}

Ошибка:
:10:13: error: use of deleted function 'std::unique_ptr::unique_ptr(const std::unique_ptr&) [with _Tp = int; _Dp = std::default_delete]'
10 | sink(std::move(p));
| ~~~~^~~~~~~~~~~~~~
In file included from /opt/compiler-explorer/gcc-14.2.0/include/c++/14.2.0/memory:78,
from :1:
/opt/compiler-explorer/gcc-14.2.0/include/c++/14.2.0/bits/unique_ptr.h:516:7: note: declared here
516 | unique_ptr(const unique_ptr&) = delete;
| ^~~~~~~~~~
:10:13: note: use '-fdiagnostics-all-candidates' to display considered candidates
10 | sink(std::move(p));
| ~~~~^~~~~~~~~~~~~~
:3:32: note: initializing argument 1 of 'void sink(std::unique_ptr)'
3 | void sink(std::unique_ptr p) {
| ~~~~~~~~~~~~~~~~~~~~~^
Compiler returned: 1

Второй пример (функция принимает std::unique_ptr по ссылке rvalue):
#include

void sink(std::unique_ptr &&p) {
// Do something with `p`
}

int main() {
auto p = std::make_unique(42);
auto f = [p = std::move(p)](){
sink(std::move(p));
};
f();
return 0;
}

Ошибка:
: In lambda function:
:10:23: error: binding reference of type 'std::unique_ptr&&' to 'std::remove_reference::type' {aka 'const std::unique_ptr'} discards qualifiers
10 | sink(std::move(p));
| ~~~~~~~~~^~~
:3:34: note: initializing argument 1 of 'void sink(std::unique_ptr&&)'
3 | void sink(std::unique_ptr &&p) {
| ~~~~~~~~~~~~~~~~~~~~~~~^
Compiler returned: 1


Подробнее здесь: https://stackoverflow.com/questions/793 ... ide-lambda
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C++»