Lambda 通过延长捕获寿命来保留指针
是否可以通过在lambda中捕获并延长lambda的寿命来延长Lambda 通过延长捕获寿命来保留指针,lambda,c++14,unique-ptr,c++17,capture-list,Lambda,C++14,Unique Ptr,C++17,Capture List,是否可以通过在lambda中捕获并延长lambda的寿命来延长唯一\u ptr的寿命 我尝试了,但在a=move(a)表达式中出现语法错误 #include <cstdio> #include <functional> #include <memory> #include <iostream> using namespace std; struct A { A() { cout << "A()" << endl; }
唯一\u ptr
的寿命
我尝试了,但在a=move(a)
表达式中出现语法错误
#include <cstdio>
#include <functional>
#include <memory>
#include <iostream>
using namespace std;
struct A {
A() { cout << "A()" << endl; }
~A() { cout << "~A()" << endl; }
};
int main() {
std::function<void ()> f;
{
std::unique_ptr<A> a(new A());
f = [a=move(a)] () mutable { return; };
}
return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
结构A{
A(){cout代码的问题是std::function
。它不是非常移动友好的,因为它需要它的可调用性,以便可以复制可构造/可分配,而lambda不是因为在您的示例中使用了仅移动的类型unique_ptr
有许多示例可以为您提供移动友好版本的std::function
我带着一个快速、黑客式、可能容易出错但“在我的机器上工作”的版本来到这里:
#include <memory>
#include <iostream>
#include <type_traits>
struct A {
A() { std::cout << "A()" << std::endl; }
~A() { std::cout << "~A()" << std::endl; }
};
template <typename Functor>
struct Holder
{
static void call(char* sbo) {
Functor* cb = reinterpret_cast<Functor*>(sbo);
cb->operator()();
}
static void deleter(char* sbo) {
auto impl = reinterpret_cast<Functor*>(sbo);
impl->~Functor();
}
};
template <typename Sign> struct Function;
template <>
struct Function<void()>
{
Function() = default;
~Function() {
deleter_(sbo_);
}
template <typename F>
void operator=(F&& f)
{
using c = typename std::decay<F>::type;
new (sbo_) c(std::forward<F>(f));
call_fn_ = Holder<c>::call;
deleter_ = Holder<c>::deleter;
}
void operator()() {
call_fn_(sbo_);
}
typedef void(*call_ptr_fn)(char*);
call_ptr_fn call_fn_;
call_ptr_fn deleter_;
char sbo_[256] = {0,};
};
int main() {
Function<void()> f;
{
std::unique_ptr<A> a(new A());
f = [a=move(a)] () mutable { return; };
}
std::cout << "Destructor should not be called before this" << std::endl;
return 0;
}
#包括
#包括
#包括
结构A{
A(){std::cout您不能在lambda中捕获对象,除非它们也是可复制的,因为lambda是可复制的,该构造函数会被删除以获得唯一性,编译器也会删除您的lambda。我明白了,实际上您需要一个不同的holder类型,感谢您的解释!