0

С++17

#include <cstdint>
#include <functional>
#include <memory>

void invoke(std::function<void()> &&act) { act(); }

int main() {
    auto uniq = std::make_unique<int>(1);
    //не компилируется
    auto lambda = [cfg = std::move(uniq)]() mutable {};

    
    invoke(std::move(lambda));
    //так компилируется
    //lambda(); 
}

Получаю ошибку, т.к. std::function внутри начинает копироваться(судя по всему). Мне не ясно почему возникает копирование, а можно ли этого как-то избежать

gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0

[ 50%] Building CXX object CMakeFiles/lambda_move_u.dir/main.cpp.o In file included from /usr/include/c++/7/functional:58:0, from /home/evgen/projects/lambda_move_u/main.cpp:2: /usr/include/c++/7/bits/std_function.h: In instantiation of ‘static void std::_Function_base::_Base_manager<_Functor>::_M_clone(std::_Any_data&, const std::_Any_data&, std::false_type) [with _Functor = main()::<lambda()>; std::false_type = std::integral_constant<bool, false>]’: /usr/include/c++/7/bits/std_function.h:227:16: required from ‘static bool std::_Function_base::_Base_manager<_Functor>::_M_manager(std::_Any_data&, const std::_Any_data&, std::_Manager_operation) [with _Functor = main()::<lambda()>]’ /usr/include/c++/7/bits/std_function.h:695:19: required from ‘std::function<_Res(_ArgTypes ...)>::function(_Functor) [with _Functor = main()::<lambda()>; = void; = void; _Res = void; _ArgTypes = {}]’ /home/evgen/projects/lambda_move_u/main.cpp:13:29: required from here /usr/include/c++/7/bits/std_function.h:192:6: error: use of deleted function ‘main()::<lambda()>::(const main()::<lambda()>&)’ new _Functor(__source._M_access<_Functor>()); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /home/evgen/projects/lambda_move_u/main.cpp:10:41: note: ‘main()::<lambda()>::(const main()::<lambda()>&)’ is implicitly deleted because the default definition would be ill-formed: auto lambda = cfg = std::move(uniq) mutable {}; ^ /home/evgen/projects/lambda_move_u/main.cpp:10:41: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete]’ In file included from /usr/include/c++/7/memory:80:0, from /home/evgen/projects/lambda_move_u/main.cpp:3: /usr/include/c++/7/bits/unique_ptr.h:383:7: note: declared here unique_ptr(const unique_ptr&) = delete; ^~~~~~~~~~

msvc19

C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include\functional(896): error C2280: 'main::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39>::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39>(const main::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39> &)': attempting to reference a deleted function E:\projects\lambda_test\main.cpp(10): note: see declaration of 'main::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39>::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39>' E:\projects\lambda_test\main.cpp(10): note: 'main::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39>::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39>(const main::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39> &)': function was implicitly deleted because a data member invokes a deleted or inaccessible function 'std::unique_ptr<int,std::default_delete>::unique_ptr(const std::unique_ptr<int,std::default_delete> &)' C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include\memory(3269): note: 'std::unique_ptr<int,std::default_delete>::unique_ptr(const std::unique_ptr<int,std::default_delete> &)': function was explicitly deleted C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include\functional(901): note: see reference to function template instantiation 'std::_Func_impl_no_allocmain::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39,_Ret>::_Func_impl_no_alloc<const _Callable&,0>(_Other)' being compiled with [ _Ret=void, _Callable=main::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39>, _Other=const main::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39> & ] C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include\functional(906): note: see reference to function template instantiation 'std::_Func_impl_no_allocmain::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39,_Ret>::_Func_impl_no_alloc<const _Callable&,0>(_Other)' being compiled with [ _Ret=void, _Callable=main::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39>, _Other=const main::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39> & ] C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include\functional(901): note: while compiling class template member function 'std::_Func_base<_Ret> *std::_Func_impl_no_allocmain::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39,_Ret>::_Copy(void *) const' with [ _Ret=void ] C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include\functional(813): note: see reference to class template instantiation 'std::_Func_impl_no_allocmain::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39,_Ret>' being compiled with [ _Ret=void ] C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include\functional(1010): note: see reference to variable template 'const bool _Is_largestd::_Func_impl_no_alloc<<lambda_a0044794c0b7998ff7e3f3c20a6f8a39,void> >' being compiled C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include\functional(1143): note: see reference to function template instantiation 'void std::_Func_class<_Ret>::_Resetmain::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39>(_Fx &&)' being compiled with [ _Ret=void, _Fx=main::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39> ] C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include\functional(1143): note: see reference to function template instantiation 'void std::_Func_class<_Ret>::_Resetmain::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39>(_Fx &&)' being compiled with [ _Ret=void, _Fx=main::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39> ] E:\projects\lambda_test\main.cpp(12): note: see reference to function template instantiation 'std::function<void (void)>::functionmain::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39,0>(_Fx)' being compiled with [ _Fx=main::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39> ] E:\projects\lambda_test\main.cpp(12): note: see reference to function template instantiation 'std::function<void (void)>::functionmain::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39,0>(_Fx)' being compiled with [ _Fx=main::<lambda_a0044794c0b7998ff7e3f3c20a6f8a39> ]

3
  • @user207200 стандарт 17, Вы мне привели ссылку на вопрос как то делать на 11
    – JK_Action
    2 мар 2022 в 14:42
  • 1
    Да, понял, у вас проблема вообще не там. Как вариант, invoke сделать шаблоном invoke(T&& act).
    – user207200
    2 мар 2022 в 14:49
  • Передаваемый в std::function вызываемый объект должен быть CopyConstructible. 2 мар 2022 в 15:39

1 ответ 1

2

std::function - копируемый, и требует того же от любого объекта, который в него кладут.

Причем неважно, копируете ли вы на самом деле этот std::function, потому что в общем случае это нельзя проверить во время компиляции.

В C++23 будет std::move_only_function, который можно только перемещать, и который не требует копируемости от объектов (а только перемещаемости).

Пока ждете C++23, можно сделать вот так: invoke(std::ref(lambda)); - это передает не копию лямбды, а ссылку на нее. Поэтому лямбда должна оставаться живой, пока вы пользуетесь этим std::function.

Ну или просто не захватывать некопируемые объекты.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.